【问题标题】:How to get method name when i know what method i call in PHP当我知道我在 PHP 中调用什么方法时如何获取方法名称
【发布时间】:2016-10-13 18:46:51
【问题描述】:

关键是我有getDates() 方法,我想将此方法的名称作为字符串获取,但不运行此方法。实际上它看起来像下一个:

$object->getResultExecutionMethod(convertmMethodNameToString($object->findDates()));

getResultExecutionMethod($methodName) {
  switch($methodName) {
    case convertmMethodNameToString($this->findDates()):
    return $getDatesStatus;
    break;

    case convertmMethodNameToString($this->anotherMethodOfThisClass()):
    return $anotherMethodOfThisClassStatus;
    break;
  }
}

在 1 个类中,我有很多方法,以及很多符合此方法执行状态的变量。调用convertmMethodNameToString() 并将我的方法放在那里我想通过这种方法获取执行状态。 那么如何实现convertmMethodNameToString() 功能呢?

【问题讨论】:

  • 您可以在上面的代码中将convertmMethodNameToString($this->findDates()替换为"findDates",并将convertmMethodNameToString($this->anotherMethodOfThisClass())替换为"anotherMethodOfThisClass"。似乎根本不需要convertmMethodNameToString 函数
  • @mario-chueca ,你的意思是这样用吗? $methodName = "findDates()"; $object->methodName(); 如果是 - 我仍然依赖硬编码每个方法名称;
  • 我不确定我是否理解这个问题,但您也可以将convertmMethodNameToString($object->findDates()) 替换为"findDates"。我完全不明白你为什么需要这种方法。也许这里缺少一些代码。

标签: php class methods


【解决方案1】:

您可能会从神奇的__call 方法中受益。您可以说,如果您需要某个方法的状态,您将调用具有相同名称但后缀为“Status”的方法。好消息是您实际上不必创建所有最后带有“状态”的方法,但可以使用陷阱。

此外,您可以使用__FUNCTION__ 来获取正在运行的函数的名称。这对于获取状态并不有趣,但可能是为了设置它。

下面是一些示例代码:

class myClass {
    // Use an array to keep the statusses for each of the methods you have:
    private $statusses = [
        "findDates" => "my original status",
        "anotherMethodOfThisClass" => "another original status"
    ];
    public function findDates($arg) {
        echo "Executing " . __FUNCTION__ . ".\n";
        // Set execution status information:
        $this->statusses[__FUNCTION__] = "last executed with argument = $arg";
    }
    // ... other methods come here

    // Finally: magic method to trap all undefined method calls (like a proxy):
    public function __call($method, $arguments) {
        // Remove the Status word at the end of the method name
        $baseMethod = preg_replace("/Status$/", "", $method);
        // ... and see if now we have an existing method.
        if(method_exists($this, $baseMethod)) {
            echo "Returning execution status for $baseMethod.\n";
            // Yes, so return the execution status we have in our array:
            return $this->statusses[$baseMethod];
        }
    }
}

// Create object
$object = new myClass();
// Execute method
$object->findDates("abc");
// Get execution status for that method. This method does not really exist, but it works
$status = $object->findDatesStatus();
echo "Status: $status\n";

上面的代码输出如下:

执行 findDates。
返回 findDates 的执行状态。
状态:最后执行参数 = abc

看到它在eval.in上运行

【讨论】:

  • 这回答了您的问题吗?你能发表评论吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-07-07
  • 1970-01-01
  • 2011-09-24
  • 1970-01-01
  • 2015-03-08
  • 2011-06-25
  • 2012-03-27
相关资源
最近更新 更多