致命错误:在不在对象上下文中时使用$ this - OOPHP

时间:2018-06-07 00:53:58

标签: php wordpress

我只是试图通过构造函数设置post_id并通过另一个函数获取该id。但是返回:Fatal error: Using $this when not in object context但是不知道为什么会发生这种情况。我之前做了很多次但是现在这个出错了。

以下是代码

class PostData
{

    private static $instance = null;
    public $post_id = 0;

    public function __construct($post_id = 0){
        if((int)$post_id > 0){
            $this->setId($post_id);
        }
    }

    private function setId($post_id){
        return $this->post_id = $post_id;
    } 
    public static function getPostID(){
        return $this->post_id;
    }

    public static function getInstance(){
        if (empty(self::$instance)) {
            self::$instance = new self();
        }
        return self::$instance;
    }
}

以及我如何称呼班级

$post = new PostData(33);
echo $post->getPostID();

但是有错误:Fatal error: Using $this when not in object context

2 个答案:

答案 0 :(得分:4)

您的问题是您在静态上下文中使用$this是不允许的。根据定义,静态函数是无对象的,$this引用对象。你需要将你的班级重组为静态或非静态。

如何使用这种结构:

class PostData
{
    public $post_id = 0;

    public function __construct($post_id = 0){
        if((int)$post_id > 0){
            $this->setId($post_id);
        }
    }

    private function setId($post_id){
        return $this->post_id = $post_id;
    } 

    public function getPostID(){
        return $this->post_id;
    }
}

根据documentation

  

因为静态方法在没有创建对象实例的情况下是可调用的,所以伪变量$ this在声明为static的方法中不可用。

再次,根据有关如何调用静态属性的文档:

  

使用箭头操作符 - >。

无法通过对象访问静态属性      

与任何其他PHP静态变量一样,静态属性只能在PHP 5.6之前使用文字或常量进行初始化;表达式是不允许的。在PHP 5.6及更高版本中,相同的规则适用于const表达式:只要可以在编译时对它们进行求值,就可以使用一些有限的表达式。

     

从PHP 5.3.0开始,可以使用变量引用该类。变量的值不能是关键字(例如self,parent和static)。

直播示例

Repl

答案 1 :(得分:1)

问题是您已将函数声明为静态,然后在静态函数中使用关键字$ this。

从您的函数中删除关键字 static 以修复:

public function getPostID(){
    return $this->post_id;
}