php对象类错误:从空值创建默认对象
每次尝试添加嵌套对象时,我都会遇到以下错误php对象类错误:从空值创建默认对象,php,object,Php,Object,每次尝试添加嵌套对象时,我都会遇到以下错误从空值创建默认对象… class api { private $authentication=null; private $status=null; private $response=null; public function __construct($user, $token) { $this->status->version=2.3; $this->authen
从空值创建默认对象…
class api {
private $authentication=null;
private $status=null;
private $response=null;
public function __construct($user, $token) {
$this->status->version=2.3;
$this->authentication->user=$user;
$this->authentication->token=$token;
}
}
我怎样才能在不出错的情况下完成这件事呢
我不想在这个特殊的事情上使用数组。这对您有帮助吗,还是我误解了
public function __construct($user, $token) {
$this->status = new stdClass(); // Here
$this->status->version=2.3;
$this->authentication = new stdClass(); // & Here
$this->authentication->user=$user;
$this->authentication->token=$token;
}
好吧,我的错。更新了,但它能工作吗?是的,它能工作。谢谢但是你能解释一下我为什么要这样做吗?我的理解是
$this->status
和$this->authentication
被设置为null(不是对象)因此,在为它们分配属性之前,必须先将它们强制转换为对象。我如何将它们强制转换为对象?为了方便起见,只需按照我的答案在构造函数中进行处理即可。