trait ClearFolder{ public function clearFolder($dir) { //codes... } public function clearInFolder($dir) { $this->clearFolder($dir); mkdir($dir); }}use boot\library\traits\ClearFolder;class FileCache{ //codes.... use ClearFolder; public static function clearAll() { //Case1. Uncaught Error: Using $this when not in object... $this->clearInFolder(self::$storage . '/'); //Case2. Non-static method boot\libr... should not be called statically self::clearInFolder(self::$storage . '/'); //Case3. Cannot instantiate trait... $trait = new ClearFolder; }}要在靜態方法中使用另一個類的非靜態方法,我必須使用 new 關鍵字創建一個實例。但是我不能使用帶有特征的“新”。我使用'declare (strict_types = 1);' 和'error_reporting(E_ALL);'。我應該靜態更改特征的方法并替換使用該特征的所有內容嗎?
1 回答

紅顏莎娜
TA貢獻1842條經驗 獲得超13個贊
如果要使用 trait 中的非靜態函數,則必須創建一個實例:
trait trait1
{
public function dummy()
{
var_dump("fkt dummy");
}
}
class c1{
use trait1;
public static function static1(){
(new static)->dummy();
}
}
c1::static1(); //string(9) "fkt dummy"
或者您將特征中的函數聲明為靜態:
trait trait1
{
public static function dummy()
{
var_dump("fkt dummy");
}
}
class c1{
use trait1;
}
c1::dummy(); //string(9) "fkt dummy"
不好,但有效。但是你不應該在不考慮你的代碼設計的情況下使用它。
- 1 回答
- 0 關注
- 144 瀏覽
添加回答
舉報
0/150
提交
取消