For example I have the following code:
function a($param)
{
function b()
{
echo $param;
}
b();
}
a("Hello World!");
That throws an E_NOTICE error because $param is of course undefined (in b()).
I cannot pass $param to b() because b() should be a callback function of preg_replace_callback(). So I had the idea to save $param in $GLOBALS.
Is there any better solution?
If you are using PHP 5.3, you could use anonymous function with use
keyword instead:
<?php
function a($param)
{
$b = function() use ($param)
{
echo $param;
};
$b();
}
a("Hello World!");
BTW, since this was tagged functional-programming: in most functional programming languages, you would just refer to param
, and it would be in scope, no problem. It's called lexical scoping, or sometimes block scoping.
It's typically languages without explicit variable declarations (eg "assign to define") that make it complicated and/or broken. And Java, which makes you mark such variables final
.
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