简体   繁体   中英

How to call function in an array after create an object in 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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM