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条)

报告相同问题?

悬赏问题

  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题