声明 $$[对象名称] 时会发生什么?
当我遇到这样的声明时,我正在尝试调试 PHP 脚本:
$cart = new form;
$$cart = $cart->function();
什么是 $$cart
?
I was trying to debug a PHP script when I came across a declaration like:
$cart = new form;
$cart = $cart->function();
What is $$cart
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
double $ 用于可变变量。
本质上,这意味着第二个 $ 以及单词是一个变量,其值用于第一个 $ 的名称,
即
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.-
当您声明
$$cart
时,PHP 所做的就是尝试获取$cart
对象的字符串值,并将其用作此变量的名称。这意味着它必须调用 其类的__toString()
魔术方法。如果类中没有 __toString() 方法,这将导致可捕获的致命错误:
否则,
$$cart
变量的名称是该对象的字符串值,如下所示由那个魔法方法返回。实现了
__toString()
魔术方法的示例(不同的类/名称,但类似于您的示例调用代码):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: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):