dougan1465 2019-07-26 02:51
浏览 65
已采纳

如何在php中创建对象后调用数组中的函数?

I've created a class Varsity and make an object of it. It's working very well when I call member function after creating object of this class. But it needs to write some extra code here.

Is it possible to call these function in an array like the last code bellow ?

    <?php
        class Varsity {
            public $miuCampus = array(
                'Manarat International University',
                'Ashulia',
                2
            );

            public function campusName() {
                echo "The university name is ".$this -> miuCampus[0];
            }

            public function campusAddress() {
                echo " situated in ".$this -> miuCampus[1];
            }

            public function campusNumber() {
                echo " and they have ".$this -> miuCampus[2];
            }
        }

        $campusData = new Varsity();
        $campusData -> campusName();
        $campusData -> campusAddress();
        $campusData -> campusNumber();
    ?>

This code is all right and working well. But this code is producing an error:

    <?php
        class Varsity {
            public $miuCampus = array(
                'Manarat International University',
                'Ashulia',
                2
            );

            public function campusName() {
                echo "The university name is ".$this -> miuCampus[0];
            }

            public function campusAddress() {
                echo " situated in ".$this -> miuCampus[1];
            }

            public function campusNumber() {
                echo " and they have ".$this -> miuCampus[2];
            }
        }

        $campusData = new Varsity();
        $campusData -> $campusInfo = array(
            'campusName()',
            'campusAddress()',
            'campusNumber()'
        );
    ?>

The first one is working well and last one is showing error. Is it possible to call function in an array like last code above?

  • 写回答

1条回答 默认 最新

  • douweibiao8471 2019-07-26 03:03
    关注

    Well you can use Variable functions

    $campusData = new Varsity();
    $campusInfo = array(
                      'campusName',
                      'campusAddress',
                      'campusNumber'
                  );
    
    for ($count = 0; $count < count($campusInfo); $count++) {
        $func_name = $campusInfo[$count];
        $campusData->$func_name();
    }
    

    See the Variable method example in the link above

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?