不使用字符串对 PHP 方法的引用


Reference to PHP method without using a string

假设我有以下PHP代码:

class Foo {
    function getBar() {
         return 1;
    }
}
function check( Foo $foo ) {
    if ( $foo->getBar() == 1 ) {
       // here could be more code ...
       return 'Oh no, there was an error in class' . 
              get_class( $foo ) . ', method ' .
              'getBar';
    }
}

check最后一个字符串困扰着我,因为如果重构工具重命名Foo::bar,错误消息将是错误的。有没有办法在不在某处使用字符串的情况下解决这个问题?

可以使用

__METHOD__获取当前方法的名称。

但是要参考其他允许您进行某种自动重构的方法 - 不,这在 php 中是不可能的。

可以使用 method_exists() 来完成

class Foo {
    function getBar() {
         return 1;
    }
}
function check( Foo $foo , $method = 'getBar') {
    if (!method_exists($foo, $method) ) {
       // here could be more code ...
       return 'Oh no, there was an error in class' . 
              get_class( $foo ) . ', method ' .
              $method;
    }
}

这在 PHP 本身中是不可能的,但你可以实现这样的功能。一种可能的实现将按如下方式工作:文件路径、类名、方法名以及某种关于位置和内容应该匹配的描述。每当触发新功能时,您的新功能都会检查给定的文件,检查某些值是否更改,修复需要修复的任何内容并记录有关任务的报告。实现这样的东西并不简单,但是,重要的是要注意有一个解决方案。