dsgk0386 2012-09-12 14:27
浏览 44
已采纳

PHP用一个字符串调用多个方法

I have the following string:

$str = "methodA()->methodB()->methodC"

And i want to call that "chain" on an object

$obj->$str

I am currently splitting with ()-> and calling one by one, but there must be abetter way.

How can i call it on one line? thanks!

EDIT: Some more context information:

I created a Doctrine Behaviour for symfony 1.4 to be able to make certain tables from the schema searchable with Zend Lucene.

In short, i need a way to say to the behaviour "To get the searchable field you must call methodA()->methodB()->methodC()"

EDIT2: Maybe i wasnt clear enough. $obj and $str are determined at runtime, so some of your suggestions are not applicable.

EDIT3: In case you are wondering, i am currently doing this:

  <?php
  $chain = explode("()->",$str);
  $method = array_shift($chain);
  $value = $obj->$method();
  foreach($chain as $method){
    $value = $value->$method();
  }
  • 写回答

6条回答 默认 最新

  • duanchu3376 2012-09-13 14:36
    关注

    After writing my comment to the main question I thought of a possible solution, though a little verbose and manual (you would have to make as many case statements as you would reasonably expect for the number of chained methods).

    function chain_execute($obj, $str) {
        $chain = explode("->",$str);
        $chain = array_map('trim', $chain);
        $chain_count = count($chain);
        switch($chain_count) {
            case 1:
                return $obj->{$chain[0]}();
                break;
            case 2:
                return $obj->{$chain[0]}()->{$chain[0]}();
                break;
            case 3:
                return $obj->{$chain[0]}()->{$chain[1]}()->{$chain[2]}();
                break;
            // etc.
            default:
                // not a value you were expecting
                throw new Exception('Invalid number of methods chained: ' . $chain_count);
                break;
        }
    }
    

    Usage would be:

    $result = chain_execute($obj, "methodA->methodB->methodC");
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(5条)

报告相同问题?

悬赏问题

  • ¥15 phython如何实现以下功能?查找同一用户名的消费金额合并—
  • ¥15 ARIMA模型时间序列预测用pathon解决
  • ¥15 孟德尔随机化怎样画共定位分析图
  • ¥18 模拟电路问题解答有偿速度
  • ¥15 CST仿真别人的模型结果仿真结果S参数完全不对
  • ¥15 误删注册表文件致win10无法开启
  • ¥15 请问在阿里云服务器中怎么利用数据库制作网站
  • ¥60 ESP32怎么烧录自启动程序,怎么查看客户esp32板子上程序及烧录地址
  • ¥50 html2canvas超出滚动条不显示
  • ¥15 java业务性能问题求解(sql,业务设计相关)