假设我有一个这样的类:
class MyClass {
public $variable;
public function __construct($variable) {
$this->variable = $variable;
}
}
,我这样调用它(没有初始化它,或者就php而言,它甚至不是一个类):
$my_class = null;
$v = $my_class->variable;
在php中是允许的吗?在大多数其他语言中,它会给出一个很大的空指针异常。如果行得通,变量的值是多少?
这是"sort of"允许的-您将获得Notice: Trying to get property of non-object
,结果将为NULL。
我不认为这样做有什么意义
这没有意义…
如果你声明了一个变量$my_class,并把它设为NULL,那么给这个变量的所有属性都是NULL。
当然,对于php,你没有做错任何事。你只是声明一个变量为空。
如果您将$my_class声明为类MyClass的对象,这将是不同的,因为您必须提供一个属性,即使这是null
class MyClass
{
public static $variable;
public function __construct($variable)
{
$this->variable = $variable;
}
}
'MyClass::$variable = null;
echo 'MyClass::$variable;