Is there a way to bind variables? PHP 5

Using PHP 5 I would like to know if a variable can dynamically refer to the value of several variables?

for example

    <?php
    $var = "hello";
    $var2 = " earth";
    $var3 = $var.$var2 ;
    echo $var3; // hello earth

Now, if I changed either $var, or $var2, I would like it to be $var3updated as well.

    $var2 =" world";  
    echo $var3; 

It still prints the evil earth, but I would like to print "hello world" now :(

Is there any way to achieve this?

+3
source share
6 answers

, PHP . - PHP, , , , , - var1 var2, , var3.

+3

. PHP 5.3 . 5.2.x.

"add" -Method, .

<?php
class MagicString {
    private $references = array();
    public function __construct(&$var1, &$var2)
    {
        $this->references[] = &$var1;
        $this->references[] = &$var2;
    }

    public function __toString()
    {
        $str = '';
        foreach ($this->references as $ref) {
            $str .= $ref;
        }
        return $str;
    }
}
$var1 = 'Hello ';
$var2 = 'Earth';

$magic = new MagicString($var1, $var2);
echo "$magic\n"; //puts out 'Hello Earth'
$var2 = 'World';
echo "$magic\n"; //puts out 'Hello World'
+3

. , - String. PHP types variables, :

. , , . , , , - . , . Expressions.

+2

, . :

$var = "hello";
$var2 = " earth";
$var3 = &$var;
$var4 = &$var2;
echo $var3.$var4; // hello earth
+1

:

$a = 'a';
$b = 'b';
$c = function() use (&$a, &$b) { return $a.$b; };
echo $c(); // ab
$b = 'c';
echo $c(); // ac
0

.

function foobar($1, $2){
$3 = "$1 $2";
return $3;
}

echo foobar("hello", "earth");
echo foobar("goodbye", "jupiter");
-1

Source: https://habr.com/ru/post/1726156/


All Articles