hhh
hhh

Reputation: 52840

PHP: how to avoid redeclaring functions?

I tend to get errors such as:

Fatal error: Cannot redeclare get_raw_data_list() (previously declared in /var/www/codes/handlers/make_a_thread/get_raw_data_list.php:7) in /var/www/codes/handlers/make_a_thread/get_raw_data_list.php on line 19

how can I avoid the error? Is it possible to create a IF-clause to check whether a function is declared before declaring it?

Upvotes: 45

Views: 40946

Answers (4)

Serj Sagan
Serj Sagan

Reputation: 30208

If you are dealing with Classes method_exists() might be what you're looking for:

if(!method_exists(__CLASS__, 'function_name')){
    function function_name(){

    }
}

This will check the current Class to make that the function function_name doesn't exist before trying to declare it

Upvotes: 5

karim79
karim79

Reputation: 342635

Use require_once or include_once as opposed to include or require when including the files that contain your functions.

The _once siblings of include and require will force PHP to check if the file has already been included/required, and if so, not include/require it again, thereby preventing 'cannot redeclare x function...' fatal errors.

Upvotes: 32

smack0007
smack0007

Reputation: 11366

"function_exists" will tell you if a function has already been declared. Though I suspect maybe you have a problem with including files more than once. When you include a file are you using require_once or include_once or just require / include?

Upvotes: 8

Dooltaz
Dooltaz

Reputation: 2463

if(!function_exists("get_raw_data_list")) {
... define function here ...
}

http://us.php.net/function_exists

Upvotes: 103

Related Questions