Why in PHP string can turn function?

Asked

Viewed 181 times

5

In the example I have a function named funcao, which aims only to display the value of the parameter on the screen.

By creating 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();

?>

Check it out at Ideone

Because I happen to be able to call the function this way?

  • 1

    Why can you ?

  • That’s the kk question, I think it’s because of the automatic typing of the php and calling with () he interprets that that string is the name of a function so try to call it. But wanted a better explanation.

  • 3

    There’s a duplicate of this. It’s hard to find

  • @bigown is the same thing as variable variables?

  • @rray I don’t know, didn’t I see that? P

  • Actually, there’s probably a duplicate but I searched and found nothing.

Show 1 more comment

2 answers

5

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

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

c

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

How PHP interprets the last line?

echo $$varb;

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

echo $vara;

replaces the second variable with its value ($stick for c);

echo c;

and prints the value on the screen

  • 1

    That was a myth, it took me 20 minutes to understand. For me you can close the question.

  • I was playing 20 minutes, I didn’t need to explain step by step. Rs

  • it was only to leave no doubt in case someone did not understand :)

4


To documentation, says that if the value of the variable is the same as that of a function, following parentheses the function of that name is invoked. This is called in php variable functions

function wow(){
    echo 'wow';
}


$function = 'wow';
$function();

Browser other questions tagged

You are not signed in. Login or sign up in order to post.