次のような宣言に出くわしたときに、PHP スクリプトをデバッグしようとしていました。
$cart = new form;
$$cart = $cart->function();
とは $$cart
?
次のような宣言に出くわしたときに、PHP スクリプトをデバッグしようとしていました。
$cart = new form;
$$cart = $cart->function();
とは $$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
ダブル$は変数変数に使用されます。
基本的に、これに伴うのは2番目の$であり、単語は変数であり、その値は最初の$の名前に使用されます。
すなわち-
$first = "second";
$second = 'Goodbye';
echo $$first; // Goodbye