简体   繁体   English

如何使用 PHP7 从静态方法调用特征的非静态方法?

[英]How can I call a trait's non-static method from a static method with PHP7?

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;

    }
}

To use a non-static method of another class inside a static method, I have to create an instance with the new keyword.要在静态方法中使用另一个类的非静态方法,我必须使用 new 关键字创建一个实例。 But I can't use 'new' with a trait.但是我不能使用带有特征的“新”。

And I use 'declare (strict_types = 1);'我使用'declare (strict_types = 1);' and ' error_reporting(E_ALL);'.和'error_reporting(E_ALL);'。

Should I change the trait's method statically and replace everything that uses the trait?我应该静态地更改特征的方法并替换使用特征的所有内容吗?

If you want to use a non static function from a trait you must create a instance:如果要使用特征中的非静态函数,则必须创建一个实例:

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"

Or you declare your function in the trait as static:或者你在 trait 中声明你的函数是静态的:

trait trait1
{
    public static function dummy()
    {
      var_dump("fkt dummy");
    }
}
class c1{
  use trait1;
} 

c1::dummy(); //string(9) "fkt dummy"

Not nice, but works.不好,但有效。 But you should not use this without thinking about your code design.但是你不应该在不考虑你的代码设计的情况下使用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM