PHP - 如何解决“不在对象上下文中使用 $this”的错误?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32053694/
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 22:46:26  来源:igfitidea点击:

PHP - How to solve error "using $this when not in object context"?

phpoop

提问by Christopher

I've this trait class:

我有这个特质类:

trait Example
{
    protected $var;

    private static function printSomething()
    {
        print $var;
    }

    private static function doSomething()
    {
        // do something with $var
    }
}

And this class:

而这个类:

class NormalClass
{
    use Example;

    public function otherFunction()
    {
        $this->setVar($string);
    }

    public function setVar($string)
    {
        $this->var = $string;
    }
}

But i'm getting this error: Fatal error: Using $this when not in object context.

但我收到此错误: Fatal error: Using $this when not in object context

How can i solve this issue? I can't use properties on a trait class? Or this isn't really a good practice?

我该如何解决这个问题?我不能在 trait 类上使用属性?或者这真的不是一个好习惯?

回答by Dmitrii Cheremisin

Your problem is connected with differences between class's methods/properties and object's.

您的问题与类的方法/属性和对象之间的差异有关。

  1. If you define propertie as static - you should obtain it through your class like classname/self/parent::$propertie.
  2. If not static - then inside static propertie like $this->propertie. So, you may look at my code:
  1. 如果您将属性定义为静态 - 您应该通过像 classname/self/parent::$properie 这样的类来获取它。
  2. 如果不是静态的 - 那么在静态属性中,如 $this->propertie。所以,你可以看看我的代码:
trait Example   
{
    protected static $var;
    protected $var2;
    private static function printSomething()
    {
        print self::$var;
    }
    private function doSomething()
    {
        print $this->var2;
    }
}
class NormalClass
{
    use Example;
    public function otherFunction()
    {
        self::printSomething();
        $this->doSomething();
    }
    public function setVar($string, $string2)
    {
        self::$var = $string;
        $this->var2 = $string2;
    }
}
$obj = new NormalClass();
$obj -> setVar('first', 'second');
$obj -> otherFunction();

Static function printSomething can't access not static propertie $var! You should define them both not static, or both static.

静态函数printSomething不能访问非静态属性$var!你应该定义它们都不是静态的,或者都是静态的。