tags:

views:

232

answers:

4

Using PHP 5 I would like to know if it is possible for a variable to dynamically reference the value of multiple variables?

For example

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

Now if I change either $var or $var2 I would like $var3 to be updated too.

    $var2 =" world";  
    echo $var3;

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

Is there any way to achieve this?

+3  A: 

No, there is no way to do this in PHP with simple variables. If you wanted to do something like this in PHP, what you'd probably do would be to create a class with member variables for var1 and var2, and then have a method that would give you a calculated value for var3.

Amber
A: 

Create a function.

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

echo foobar("hello", "earth");
echo foobar("goodbye", "jupiter");
superUntitled
i think you missed the point.
Zac Bowling
+2  A: 

No. Cannot be done without utilizing some sort of custom String class. Check the PHP manual for types and variables, especially this passage:

By default, variables are always assigned by value. That is to say, when you assign an expression to a variable, the entire value of the original expression is copied into the destination variable. This means, for instance, that after assigning one variable's value to another, changing one of those variables will have no effect on the other. For more information on this kind of assignment, see the chapter on Expressions.

Gordon
+1  A: 

This should do the trick. I tested it on PHP 5.3 and it worked. Should also work on any 5.2.x version.

You could easily extend this with an "add"-Method to allow an arbitrary number of strings to be placed in the object.

<?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'
Techpriester
both evil and neat at the same time.
Zac Bowling