Oleg Popov
Oleg Popov

Reputation: 2514

PHP Class function declaration issue

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.

Upvotes: 2

Views: 160

Answers (4)

gen_Eric
gen_Eric

Reputation: 227280

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 the class global 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 the use keyword).

class myClass {

    function abc() {
        $internal = function() {
            return "i am internal"; 
        };

        return $internal();
    }
}

You can also declare internal as a private function of the class, especially if it's not going to change. Why keep re-making a function?

class myClass {

    private function internal(){
        return "i am internal"; 
    }

    function abc() {
        return $this->internal();
    }
}

Upvotes: 1

Michal M
Michal M

Reputation: 9480

Check whether the function exists prior to defining it:

class myClass {
    function abc() {
        if ( ! function_exists('internal')) {
            function internal() {
                return "i am internal"; 
            }
        }

        return internal();
    }
}

Upvotes: 1

goto-bus-stop
goto-bus-stop

Reputation: 11824

Alternatively:

if (!function_exists('internal')) { function internal ... }

However, you have to be aware that in this case, the function internal will be available outside the class scope as well. Lawrence's solution is a better approach.

Upvotes: 0

Lawrence Cherone
Lawrence Cherone

Reputation: 46620

You cant redeclare the function period so try something like this:

<?php 
class myClass {

    function abc() {
        return $this->internal();
    }

    private function internal() {
        return "i am internal";
    }

}
?>

Upvotes: 5

Related Questions