【问题标题】:Is there a way to get a class name in php, convert it into a string and store it in a variable?有没有办法在 php 中获取类名,将其转换为字符串并将其存储在变量中?
【发布时间】:2017-12-17 09:50:55
【问题描述】:

我有一个带有方法 saveToTable($table) 的类 Bar,我需要为 $table 设置一个默认值,但该值需要是动态的,动态值应该是 Bar 扩展至的类的名称。

class Bar {

  public function saveToTable($table) {

  }

}



class Foo extends Bar {

}

$bar = new Foo;

$bar->saveToTable(); // in which case saveToTable() would have a param of 'foo' i.e. saveToTable('foo');

我目前使用的解决方案是在每个扩展 Bar 的类中明确指定一个 $table 属性,并为其分配这些类名称的字符串值,但这会破坏使我的应用程序动态化的目的,加上它会很麻烦而且容易出错。

【问题讨论】:

  • 这真是糟糕的设计。不要将业务逻辑与类名称等实现细节混为一谈。
  • 好的,我明白了,那你有什么建议?

标签: php oop


【解决方案1】:

您可以使用 late static binding 来完成,它将引用扩展类

将此方法添加到您的 Bar 类中

 class Bar{

   public function getClassName()
   {
      return static::class;
   }
 }

现在你可以得到名字了

$bar = new Foo();

$bar->getClassName(); // returns Foo

【讨论】:

    【解决方案2】:

    另一种解决方案,注意命名空间,也许你需要删除

    class Bar
    {
        public function saveToTable()
        {
            //Without namespace
            $table = substr(static::class, strlen(__NAMESPACE__) + 1);
            //With namespace
            $table = static::class;
        }
    }
    
    class Foo extends Bar
    {
    }
    
    $bar = new Foo;
    $bar->saveToTable();
    

    【讨论】:

      【解决方案3】:

      而不是为您的方法使用具有默认值的参数(不能动态分配) 考虑使用这样的东西:

      class Bar {
      
          protected $classname;
      
          public function __construct() {
              $this->classname = static::class;
          }
      
          public function saveToTable() {
              echo $this->classname;
          }
      }
      

      现在在 saveTotable() 中,你的类名是字符串。

      class Foo extends Bar {
      
      }
      
      $bar = new Foo;
      
      $bar->saveToTable(); // will echo 'Foo'
      

      【讨论】:

        猜你喜欢
        • 2011-03-05
        • 1970-01-01
        • 1970-01-01
        • 2013-08-02
        • 2022-07-26
        • 2019-04-08
        • 2021-05-25
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多