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";
}
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:
<?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:
$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