php对象类错误:从空值创建默认对象

8 浏览
0 Comments

php对象类错误:从空值创建默认对象

每次我尝试添加嵌套对象时,都会出现以下错误从空值创建默认对象...

class api {
    private $authentication=null;
    private $status=null;
    private $response=null;
    public function __construct($user, $token) {
        $this->status = new stdClass();
        $this->status->version=2.3; 
        $this->authentication = new stdClass();
        $this->authentication->user=$user;
        $this->authentication->token=$token;
    }
}

如何在不出现此错误的情况下实现相同的功能?

我不想对特定的事情使用数组。

0
0 Comments

问题的原因是在构造函数中,$this->status和$this->authentication被设置为null,而不是对象。因此,在给它们赋值之前,需要将它们转换为对象。解决方法是在构造函数中将它们强制转换为对象。

具体的代码如下:

public function __construct($user, $token) {
    $this->status = new stdClass(); // 将$this->status转换为对象
    $this->status->version = 2.3; 
    $this->authentication = new stdClass(); // 将$this->authentication转换为对象
    $this->authentication->user = $user;
    $this->authentication->token = $token;
}

这样,$this->status和$this->authentication就被正确地设置为对象,可以正常地给它们赋值了。

这个问题的解决方法就是在构造函数中将变量强制转换为对象。这样做的原因是因为在构造函数中,这些变量被默认设置为null,而不是对象。因此,需要将它们转换为对象,才能正常地给它们赋值。

希望这个解答对你有所帮助。如果还有其他问题,请随时提问。

0