【发布时间】:2019-12-04 05:47:15
【问题描述】:
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);'。
我应该静态更改 trait 的方法并替换所有使用 trait 的东西吗?
【问题讨论】:
-
如果你想这样做,你的整体代码设计就有问题。另外,不,答案是否定的,因为您不能实例化特征。
-
特征不是类。我建议通读 the manual about traits:“无法单独实例化 Trait”.
-
据我所见,您正在尝试将特征用作辅助方法的命名空间。您可以考虑将特征转换为类并将此特征的公共方法转换为静态方法。尽管此代码设计无论如何都不是完美无缺的,但与您现在所拥有的相比,它要好得多。
标签: php static-methods traits