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

PHP-如何解决错误“;当不在对象上下文中时使用$this“;?,php,oop,Php,Oop,我有这样的特点: trait Example { protected $var; private static function printSomething() { print $var; } private static function doSomething() { // do something with $var } } 这门课: class NormalClass { use Ex

我有这样的特点:

trait Example
{
    protected $var;

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

    private static function doSomething()
    {
        // do something with $var
    }
}
这门课:

class NormalClass
{
    use Example;

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

    public function setVar($string)
    {
        $this->var = $string;
    }
}
但我得到了一个错误:
致命错误:不在对象上下文中时使用$this


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

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

  • 如果您将属性定义为静态的,那么应该通过classname/self/parent::$property之类的类来获取它
  • 如果不是静态的,那么在静态属性中,比如$this->property。 因此,您可以查看我的代码:
  • 静态函数printSomething无法访问非静态属性$var!
    您应该将它们都定义为非静态,或者都定义为静态。

    您在哪里/如何调用setvar()?要获得该错误,您必须执行类似于
    $foo=NormalClass::setVar()
    之类的操作。对于您的printSomething,
    $var
    将是一个未定义的局部变量。@MarcB我已经更新了我的问题。这没有帮助,现在它变成了“如何/在哪里调用otherFunction()”?您需要显示整个调用链。您的意思可能是
    print static::$var,因为该方法是静态的。实例变量对您没有帮助。您将实例变量(属于类实例的一部分)与类变量(属于类本身的静态变量)混合使用,
    $this->var VS.self::$var
    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();