【发布时间】: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->test($str);。
标签: php static-methods