views:

36

answers:

1

i trying to debug a php script and came across a declaration like

$cart = new form;
$$cart = $cart->function();
+1  A: 

What PHP does when you declare $$cart, is try to get the string value of the $cart object, and use that as the name for this variable variable. This means it'd have to call the __toString() magic method of its class.

If there is no __toString() method in the class, this will cause a catchable fatal error:

Catchable fatal error: Object of class MyClass could not be converted to string...

Otherwise, the name of the $$cart variable variable is the string value of the object as returned by that magic method.

An example with the __toString() magic method implemented (different classes/names but similar to your example calling code):

class MyClass {
    public function __toString() {
        return 'foo';
    }
    public function some_method() {
        return 'bar';
    }
}

$obj = new MyClass();
$$obj = $obj->some_method();

echo (string) $obj, "\n"; // foo
echo $$obj; // bar
BoltClock