php - fatal error : Using $this when not in object context - OOPHP

标签 php wordpress

我只是想通过构造函数设置 post_id 并通过另一个函数获取该 id。但它正在返回: fatal error :不在对象上下文中时使用 $this 但不知道为什么会这样正在发生。我以前做过很多次,但现在出了问题。

代码如下

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;
    }
}

我是如何称呼这个类(class)的

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

但是出现错误: fatal error :不在对象上下文中时使用 $this

最佳答案

您的问题是您在不允许的静态上下文中使用 $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 :

Because static methods are callable without an instance of the object created, the pseudo-variable $this is not available inside the method declared as static.

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

Static properties cannot be accessed through the object using the arrow operator ->.

Like any other PHP static variable, static properties may only be initialized using a literal or constant before PHP 5.6; expressions are not allowed. In PHP 5.6 and later, the same rules apply as const expressions: some limited expressions are possible, provided they can be evaluated at compile time.

As of PHP 5.3.0, it's possible to reference the class using a variable. The variable's value cannot be a keyword (e.g. self, parent and static).

实例

Repl

关于php - fatal error : Using $this when not in object context - OOPHP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50731551/

相关文章:

css - 如何在 Wordpress 中编辑 CU3ER 字幕的样式?

php - WordPress Cron API 是否在后台运行?

php - 我可以 'drop' 一个 PHP 请求而不回复吗?

php - 在 PHP 中使用 JS 变量

php - Nginx + Xamp + SSL 奇怪的行为

wordpress - 在 Laravel 中获取最近的 wordpress 帖子

javascript - jQuery 点击不触发

php - 使用json_encode发送html最后返回 “null”字符串

php - 带有 AM 和 PM 的字符串在 php 中的日期格式

PHP上传CSV以更新数据库记录但排除重复