如何通过变量调用函数

I hope this question is not too simple, but I have no idea how to do this

$book = 'book';
$car = 'car';

function $book()
{ 
 return "Hello, world!";
}
function $car()
{
 return "WoW , The red car";
}

You can call a function with variable name like this:

Variable functions

<?php
    $a = 'book';

    function book() {
        echo 'book function';
    }

    // this is equivalent to book()
    $a();

So to expand a little bit:

<?php
$functions = ['book', 'car'];

function book() {
    return "Hello, world!";
}

function car() {
    return "WoW , The red car";
}

foreach ($functions as $function) {
    echo $function() .'<br>';
}

The OUTPUT would be:

Hello, world!
WoW , The red car

Another way of doing it to get same output:

Anonymous functions

$book = function() {
    echo 'book function';
};

$book();

In this case, the above function doesn't have an actual name and is represented by a variable.

And let me give you an example:

<?php
    $book = function() {
        echo 'book function';
    };

    $a = $book;

    echo $a();

So, to expand in the same manner:

<?php
$functions = ['book', 'car'];

$book = function () {
    return "Hello, world!";
};

$car = function() {
    return "WoW , The red car";
};

foreach ($functions as $function) {
    echo ${$function}(). '<br>';
}

DEMO:

http://sandbox.onlinephpfunctions.com/code/1972f1acd72984d459efbfb308680aaa9d7a1fad

You can write an anonymous function:

$book = function() { 
    return "Hello, world!";
};
echo $book(); // invoke it

You cant do that, you have 2 options.

A couple of ways:

Use variable functions:

<?php
$book = 'book';
$car = 'car';

function book()
{ 
 return "Hello, world!";
}

function car()
{
 return "WoW , The red car";
}

echo $book();
echo $car();

Or closures:

<?php
$book = function () { 
 return "Hello, world!";
};

$car = function() {
 return "WoW , The red car";
};

echo $book();
echo $car();

Class

 class foo
 {
     public function __invoke(){ echo "hello"; }
 }

Test

 $obj = new foo;
 $obj();

Output

hello

Online Sandbox

You can also use reflection (to call an existing function as a string)

 (new ReflectionFunction('print_r'))->invoke("hello");

Outputs

  hello

ReflectionMethod is nice too, because it maintains state of the object, for example

 class foo{

     protected $bar;

     public function setBar($bar){ $this->bar = $bar;}

     public function bar(){ echo $this->bar; }
 }


 $obj = new foo;

 $obj->setBar("good bye");

 (new ReflectionMethod($obj, 'bar'))->invoke($obj);

Outputs

good bye