Why in PHP string can turn function?

5

In the example I have a function with name of funcao , which is intended only to display the value of the parameter on the screen.

When you create a string with the function name and call it as a function, it will be executed:

<?php

function funcao($parametro = "default") {
    echo $parametro . "<br/>\n" ;
}

$func = "funcao"; 
$func("kirotawa");

$func = "FUNCAO";
$func();

?>

See on Ideone

Why can I call the function as follows?

    
asked by anonymous 29.01.2016 / 17:33

2 answers

4

The documentation , says that if the value of the variable is the same as some function, following from parentheses the function of such name is invoked. This is called in the php of variable functions

function wow(){
    echo 'wow';
}


$function = 'wow';
$function();
    
29.01.2016 / 17:40
5

The same works with variable variables, the name is kind of strange, but it exists as in the example below:

$vara = "c";
$varb = "vara";
echo $$varb;
  

c

This happens because you can use the value of a variable to call functions, or access other variables, thus ensuring greater language flexibility

How does PHP interpret the last line?

echo $$varb;

replaces the first variable by its value ($ varb per stick);

echo $vara;

replaces the second variable by its value ($ vara by c);

echo c;

and prints the value on the screen

    
29.01.2016 / 17:47