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

Chr*_*her 4 php oop

我有这个特质课:

trait Example
{
    protected $var;

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

    private static function doSomething()
    {
        // do something with $var
    }
}
Run Code Online (Sandbox Code Playgroud)

而这堂课:

class NormalClass
{
    use Example;

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

    public function setVar($string)
    {
        $this->var = $string;
    }
}
Run Code Online (Sandbox Code Playgroud)

但是我得到了这个错误: Fatal error: Using $this when not in object context.

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

小智 12

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

  1. 如果将属性定义为static - 您应该通过类来获取它,如classname/self/parent :: $ propertie.
  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();
Run Code Online (Sandbox Code Playgroud)

静态函数printSomething无法访问非静态属性$ var!您应该将它们定义为非静态或静态.