i have an issue with function redeclaration problem. So, i am trying to call multiple times this example.
class myClass {
function abc() {
function internal() {
return "i am internal";
}
return internal();
}
}
$myClass = new myClass();
echo $myClass->abc();
echo $myClass->abc(); // HERE IS THE PROBLEM when i call same function second time
PHP showing Fatal error: Cannot redeclare internal() (previously declared).
Does anyone have an idea how can i solve this issue?
Thanks in advance.
When you declare a function using
function <name>(), you are not declaring it in the scope you think you are. That function is being declared in theclassglobal scope, not the function/class scope.See the PHP Docs: http://www.php.net/manual/en/functions.user-defined.php#example-149
So, when you call
abc, you are re-declaring the global function,internal.If you want to do what you are doing, you can use closures instead (NOTE: This only works in PHP 5.3+). This has the benefit of being able to read local variables from within
abc(if you use theusekeyword).You can also declare
internalas a private function of the class, especially if it’s not going to change. Why keep re-making a function?