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

标签 php static-methods traits

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 关键字创建一个实例。但我不能将“new”与特征一起使用。

我使用“declare (strict_types = 1);”和“error_reporting(E_ALL);”。

我应该静态更改特征的方法并替换使用该特征的所有内容吗?

最佳答案

如果您想使用特征中的非静态函数,您必须创建一个实例:

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"

不太好,但是可以。但您不应该在没有考虑代码设计的情况下使用它。

关于php - 如何使用 PHP7 从静态方法调用特征的非静态方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59169625/

相关文章:

php - XAMPP 7.0.6 中的 api-ms-win-crt-runtime-l1-1-0.dll 丢失错误

php - 如何使用 WooCommerce 成员(member) Hook

F# 多行静态方法

C# 静态方法与对象实例

PHP 特征 : How to resolve a property name conflict?

generics - Rust:实现通用特征时出现 E0562

PHP、MySQL 错误 : Column count doesn't match value count at row 1

php - Laravel 扩展 TestResponse 类

java - 无法对非静态方法进行静态引用

scala - 为什么子特征中需要 "abstract override"而不是单独的 "override"?