【问题标题】:Differentiate between methods in a class based on the naming convention?根据命名约定区分类中的方法?
【发布时间】:2013-04-10 17:51:05
【问题描述】:

这是场景:

我有一个没有预定数量的方法的类。有些是function actionName,有些是function filterName,其中"filter""action" 将定义它们是什么类型的方法,"Name" 可以是任何东西。

在我的__construct() 我想:

$methods = get_class_methods($this);

foreach ( $methods as $method ) {

  if ( $method == 'action' )
    $this->DoSomething( $this->{$method}() );

  if ( $method == 'filter' )
    $this->DoSomethingElse( $this->{$method}() );

}

如何在不使用任何类型的字符串或 reg 表达式的情况下实现这一点?

我也愿意使用get_class_methods() 的替代品。但请记住,我永远不会知道有多少 "action""filter" 方法存在。

【问题讨论】:

    标签: php class methods


    【解决方案1】:
    if (substr($method,0,6) == "action") { }
    
    if (substr($method,0,6) == "filter") { }
    

    我只是检查关键字函数名称的前六个字符链。请注意 - 过多的关键字会影响效果。

    【讨论】:

    • 我可能读错了,但主要原因是我不想使用任何类型的 str 搜索,因为如果您查看Benchmarks,它给人的印象是仅 80 个循环大约需要 1 秒.对我来说,这听起来像是一大堆开销......在我的例子中,我很可能有超过 100 种方法。这是我永远无法预测或知道的事情。
    • 就“其他方法”而言,我很少见到能够在不实际使用任何类型的字符串比较的情况下识别字符串的方法。没有你可以使用的方便的标志,所以唯一剩下的就是一个查找表:-(
    • 基本上我想做function {type}name () {}然后if ( functionType($fName) == 'action' ) {...}
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-31
    • 1970-01-01
    • 1970-01-01
    • 2023-04-02
    • 1970-01-01
    • 2019-06-19
    相关资源
    最近更新 更多