Search code examples
phphtmlvariablesreturnecho

Is it possible to insert one variable inside another in php?


I'm working on a personal project, I do it as a hobby, I like the world of programming but I'm not very good. So I would like to understand more about the issue I am in.

I was wondering if it was possible to put one variable inside another. Let me explain better with some examples.

I know I can do this:

$var1 = $item->get_something();
$var2 = $var1->get_anything();

echo '<div class="custom"> '. $var2 .' </div>

But I can't do something like that:

$var2 = ( $var1 = $item->get_something() ?? $var1->get_anything() );
echo '<div class="custom"> '. $var2 .' </div>

Is it possible to define $ var1 inside $ var2? So that $ var2 contains both $ var1 something and $ var1 anything. I understand this is a horror, pardon my ignorance. But is something like this possible ?


Solution

  • Thanks to Andrea Olivato.

    Not 100% sure I understand what you mean but it seems you're looking to do everything in one instruction and you could do $item->get_something()->get_anything() – Andrea Olivato

    After several tests I managed to get a result. I understood that I can also do as written below.

    $var2 = $var1 = $item->get_something()->get_anything();
    echo '<div class="custom"> '. $var2 .' </div>