加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

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

发布时间:2020-12-13 21:58:31 所属栏目:PHP教程 来源:网络整理
导读:我有这个特质课: trait Example{ protected $var; private static function printSomething() { print $var; } private static function doSomething() { // do something with $var }} 而这堂课: class NormalClass{ use Example; public function otherF
我有这个特质课:

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.

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

解决方法

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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读