php 错误:不在对象上下文中使用 $this

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19261189/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 19:08:00  来源:igfitidea点击:

Error: Using $this when not in object context

phpclassmethodsstatic-methods

提问by Leo Houer

I have looked for other questions covering this error, but could not find a case that applies to my problem.

我已经寻找了涵盖此错误的其他问题,但找不到适用于我的问题的案例。

Basically the static method in my class invokes a non-static method which in return invokes another non-static method.

基本上,我的类中的静态方法调用一个非静态方法,该方法反过来调用另一个非静态方法。

This throws an Fatal error:

这会引发致命错误:

Fatal error: Using $this when not in object context in class.php on line ...

致命错误:当不在 class.php 中的对象上下文中时使用 $this 在线...

I can't figure out why it is not okay to call a non-static class method from another non-static class method via $this. Is it because they are both invoked from a static function and hence there is no $this instance ?

我不明白为什么通过 $this 从另一个非静态类方法调用非静态类方法是不行的。是因为它们都是从静态函数调用的,因此没有 $this 实例吗?

Here is the (simplified) class:

这是(简化的)类:

class Redis_Provision {

    public $redis = NULL;

    public function redis_query()
    {
        if(is_null($this->redis)) {
            $this->setBackend();   <------- This throws the fatal error
        }
        return $this->redis;
    }

    public function setBackend()
    {
        $this->redis = new Redis();
        $this->redis->connect();
    }

    public static function activate()
    {

        if( self::redis_query()->ping())
        {
            // Do stuff
        }
    }
}

Which i would invoke via:

我将通过以下方式调用:

$redis_provision = new Redis_Provision();
$redis_provision->activate();

采纳答案by George Brighton

The error occurs because you've called a non-static method statically (this will have risen an E_STRICT- check your error reporting), which doesn't stop execution but means there's no object context ($thiscannot be used).

发生错误是因为您静态调用了一个非静态方法(这将引发E_STRICT- 检查您的错误报告),这不会停止执行,但意味着没有对象上下文($this无法使用)。

The proper way to fix the error is to instantiate the class in activate(), and call the redis_query()method on the object, e.g.

修复错误的正确方法是在 中实例化类activate(),并调用redis_query()对象上的方法,例如

$redis_provision = new Redis_Provision();
if($redis_provision->redis_query()->ping()) { ... }

This means that redis_query()executes with a context, and so functions normally.

这意味着redis_query()使用上下文执行,因此正常运行。

Also, the activate()method is static, so you don't need to create a new object in your invocation code. You can just call Redis_Provision::activate()directly.

此外,该activate()方法是静态的,因此您无需在调用代码中创建新对象。Redis_Provision::activate()直接打电话就可以了。