开发者

What happens when $$[object name] is declared?

I was trying to debug a PHP script when I came across a declaration like:

$cart = new form;
$$ca开发者_如何转开发rt = $cart->function();

What is $$cart?


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


the double $ is used for a variable variable.

essentially what this entails is the second $ along with the word is a variable the value of which is used for the name of the first $

i.e.-

$first  = "second";

$second = 'Goodbye';

echo $$first; // Goodbye
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜