Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use Variable as Function Name in PHP [duplicate]

Possible Duplicate:
Use a variable to define a PHP function

Is there a way of using a variable as a function name.

For example i have a variable

$varibaleA; 

and I want to create a function i.e.

function $variableA() { } 

so this function can be called later in the script. Does anyone know if this can be done?

Thanks

like image 849
Carl Thomas Avatar asked Dec 11 '11 18:12

Carl Thomas


People also ask

How do you call a function variable in PHP?

Summary. Append parentheses () to a variable name to call the function whose name is the same as the variable's value. Use the $this->$variable() to call a method of a class. Use the className::$variable() to call a static method of a class.

Can you reuse variable names in different functions?

Therefore, in your case, the variables will be passed from the main driver to the individual functions by reference. So, yes, you can have variables of the same name in different scopes.

How can use variable in one function in another PHP?

You need to instantiate (create) $newVar outside of the function first. Then it will be view-able by your other function. You see, scope determines what objects can be seen other objects. If you create a variable within a function, it will only be usable from within that function.

What is dynamic function PHP?

Dynamic Function CallsIt is possible to assign function names as strings to variables and then treat these variables exactly as you would the function name itself. Following example depicts this behaviour.


Video Answer


2 Answers

Declaring a function with a variable but arbitrary name like this is not possible without getting your hands dirty with eval() or include().

I think based on what you're trying to do, you'll want to store an anonymous function in that variable instead (use create_function() if you're not on PHP 5.3+):

$variableA = function() {     // Do stuff }; 

You can still call it as you would any variable function, like so:

$variableA(); 
like image 148
BoltClock Avatar answered Oct 06 '22 01:10

BoltClock


$x = 'file_get_contents'; $html = $x('http://google.com'); 

is functionally equivalent to doing

$html = file_get_contents('http://google.com'); 

They're called variable functions, and generally should be avoided as they're too far removed from variable variables.

like image 38
Marc B Avatar answered Oct 06 '22 01:10

Marc B