dongzhuang1923 2014-07-14 09:54
浏览 31
已采纳

如何在PHP中按字符串调用(执行)方法?

Example:

final class A
{
    public static $instance;
    public static function get()
    {
        if (self::$instance === null)
            self::$instance = new self();
        return self::$instance;
    }
    public static function b()
    {
        return array('a','b','c');
    }
}

And Need to call the following method by string:

$callString = 'A::get()->b()';

How to call this via string?

  • 写回答

2条回答 默认 最新

  • douhao9203 2014-07-14 10:01
    关注

    Have you actually tried something? It's as simple as this:

    final class A
    {
        public static $instance;
        public static function get()
        {
            if (self::$instance === null)
                self::$instance = new self();
            return self::$instance;
        }
        public static function b()
        {
            return array('a','b','c');
        }
    }
    
    $class = 'A';//class name
    $getter = 'get';//static method
    $method = 'b';//public method
    $instance = $class::getter();//calls A::get()
    $array = $instance->{$method}();//gets array
    //check with:
    var_dump(
        $class::$getter()
            ->{$method}()
    );
    

    If you only have this string (A::get()->b()) to go on, you'll have to process/parse that string, and take it from there. A simple, but crude way to do so would be through regex:

    $str = 'A::get()->b()';
    preg_match_all('/(.+?)(::|\(\)-?>?)/', $str, $matches)
    {
        $operators = $matches[2];//array('::', '()->', '()')
        $operands = $matches[1];//array('A', 'get', 'b');
        $result = null;
        for ($i=0, $j=count($operands);$i<$j;++$i)
        {
            $result = $operands[$i];//
            switch ($operator[$i])
            {
                case '::':
                    $member = $operand[++$i];//next operand
                    if (substr($opertator[$i],0,2) === '()')
                        $result = $result::$member();
                    else
                        $result = $result::{$member};//static property
                    break;
                case '()->'://non-static access
                case '()':
                    $result = $result->{$operand[$i]}();
                    break;
                default:
                    $result = $result->{$operand[$i]};//non-static property
            }
        }
    }
    

    Note that this is un-tested, and very rough around the edges, but it should be enough to get you started.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据
  • ¥20 软件测试决策法疑问求解答