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 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大
  • ¥15 import arcpy出现importing _arcgisscripting 找不到相关程序
  • ¥15 onvif+openssl,vs2022编译openssl64