且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-11-14 23:39:40

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

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

  1. 如果您将属性定义为静态-您应该通过类(例如classname/self/parent :: $ propertie)获得它.
  2. 如果不是静态的,则在静态属性内,例如$ this-> propertie. 因此,您可以看一下我的代码:
  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:

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! 您应该将它们定义为非静态或静态.

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