嗨,我有這個錯誤的示例代碼。
例外:使用$這個時候不是在對象上下文
<?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'。 – FirstOne
我如何重構代碼?在靜態方法內實例化類A?這是一個好習慣嗎? –
刪除靜態並嘗試 –