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
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.
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.
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.
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.
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();
$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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With