[英]Access of variable in a null php class
Say that I have a class like this: 假设我有这样的课程:
class MyClass {
public $variable;
public function __construct($variable) {
$this->variable = $variable;
}
}
and I call it like this (without initializing it, or as far as php is concerned it's not even a class): 而且我这样称呼它(无需初始化它,或者就php而言,它甚至不是一个类):
$my_class = null;
$v = $my_class->variable;
Is this allowed in php? 这是PHP允许的吗? It would give a big fat null pointer exception in most other languages.
在大多数其他语言中,它将给出一个大的胖空指针异常。 If it works, what's the value of variable?
如果可行,变量的值是多少?
It is "sort of" allowed - you will get a Notice: Trying to get property of non-object
and the result will be NULL. 它是“允许的”-您将得到一个
Notice: Trying to get property of non-object
结果将为NULL。
I anyway don't see a point of doing that. 无论如何,我看不出这样做的意义。
That doesn't make sense... 那没有道理...
If you declare a variable $my_class, and makes it NULL, every attribute given to that variable is null. 如果声明变量$ my_class并将其设置为NULL,则赋予该变量的每个属性均为null。
Of course, for php you're not doing anything wrong. 当然,对于php,您没有做错任何事情。 You're just declaring that a variable is null.
您只是在声明变量为空。
This would be different if you declare $my_class as an object of your class MyClass, because you must give an attribute, even if this is null 如果将$ my_class声明为类MyClass的对象,则将有所不同,因为即使该属性为null,也必须提供一个属性。
class MyClass
{
public static $variable;
public function __construct($variable)
{
$this->variable = $variable;
}
}
\MyClass::$variable = null;
echo \MyClass::$variable;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.