【问题标题】:PHP Error - Exception: Using $this when not in object contextPHP 错误 - 异常:不在对象上下文中使用 $this
【发布时间】:2017-06-11 13:22:58
【问题描述】:

您好,我在使用此示例代码时遇到此错误。

例外:不在对象上下文中使用 $this

<?php

Class A {
 public function test($str)
 {
     return trim($str);
 }
}


Class B {

 protected $trim;   
 public function __construct(A $trim){  
     $this->trim = $trim;
 }   

 public static function trim_str($str)
 {
     return $this->trim->test($str);
 }
}

//implementation
B::trim_str(" TRIM ME ");

?>

任何人都可以启发我。 谢谢

【问题讨论】:

  • $this 指的是给定对象的实例。但是静态与实例并没有真正的关系,所以不能在静态方法中使用$this
  • 如何重构代码?在静态方法中实例化 A 类?这是一个好习惯吗?
  • 去掉静电试试
  • @sonal 我的目标是成为一个帮助类。我选择将它用作静态,所以我不会每次调用它时都实例化它。
  • trim_str的内容替换为$a = new A(); return $a-&gt;test($str);

标签: php static-methods


【解决方案1】:
Class B
{

    protected $trim;

    public function __construct(A $trim)
    {
        $this->trim = $trim;
    }

    public static function trim_str($str)
    {
        return $this->trim->test($str); //You Cannot access $this here
    }
}

可能的解决方案

$trim 变量更改为静态

Class B
{
    protected static $trim;

    public function __construct(A $trim)
    {
        static::$trim = $trim;
    }

    public static function trim_str($str)
    {
        return static::$trim->test($str);
    }
}

【讨论】:

    【解决方案2】:

    您不能在类中的静态方法的上下文中使用$this,因为它不属于一个实例,这就是错误发生的原因。

    根据 PHP 手册:

    因为静态方法可以在没有类实例的情况下调用,所以伪变量 $this 在声明为静态的方法中不可用。

    简要说明请参考 PHP 手册文档 (http://php.net/manual/en/language.oop5.static.php)

    【讨论】:

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