【问题标题】:PHP - How to solve error "using $this when not in object context"?PHP - 如何解决“不在对象上下文中使用 $this”的错误?
【发布时间】:2015-08-17 15:01:02
【问题描述】:

我有这个特质类:

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

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

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

【问题讨论】:

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

标签: php oop


【解决方案1】:

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

  1. 如果您将属性定义为静态 - 您应该通过您的类访问它,例如 classname/self/parent::$property
  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();

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

【讨论】:

    猜你喜欢
    • 2017-09-21
    • 1970-01-01
    • 2011-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多