PHP-如何解决错误“不在对象上下文中时使用$ this"? [英] PHP - How to solve error "using $this when not in object context"?

查看:117
本文介绍了PHP-如何解决错误“不在对象上下文中时使用$ this"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个特质课程:

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.

But i'm getting this error: 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?

推荐答案

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

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.

这篇关于PHP-如何解决错误“不在对象上下文中时使用$ this"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆