我怎样才能称一种特质为';从PHP7的静态方法到非静态方法?
要在静态方法中使用另一个类的非静态方法,我必须使用new关键字创建一个实例。但我不能用“新”来形容一个特质 我使用“declare(strict_types=1);”和“错误报告(E_ALL)”我怎样才能称一种特质为';从PHP7的静态方法到非静态方法?,php,static-methods,traits,Php,Static Methods,Traits,要在静态方法中使用另一个类的非静态方法,我必须使用new关键字创建一个实例。但我不能用“新”来形容一个特质 我使用“declare(strict_types=1);”和“错误报告(E_ALL)” 我是否应该静态更改trait的方法并替换使用该trait的所有内容?如果要使用trait的非静态函数,必须创建一个实例: use boot\library\traits\ClearFolder; class FileCache { //codes.... use ClearFolde
我是否应该静态更改trait的方法并替换使用该trait的所有内容?如果要使用trait的非静态函数,必须创建一个实例:
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;
}
}
或者将trait中的函数声明为static:
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”。从我所看到的情况来看,您正试图使用Trait作为helper方法的名称空间。您可以考虑将特性转换为类和公共特性的方法,并将其转换为静态方法。尽管这种代码设计无论如何都不是完美无缺的,但它比您现在拥有的要好得多。
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"