PHP:如何避免重新声明函数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1384006/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 02:18:35  来源:igfitidea点击:

PHP: how to avoid redeclaring functions?

phpfunctiondeclaration

提问by hhh

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

致命错误:无法在第 19 行的 /var/www/codes/handlers/make_a_thread/get_raw_data_list.php 中重新声明 get_raw_data_list()(之前在 /var/www/codes/handlers/make_a_thread/get_raw_data_list.php:7 中声明)

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

我怎样才能避免这个错误?是否可以创建一个 IF 子句来在声明之前检查函数是否已声明?

采纳答案by karim79

Use require_onceor include_onceas opposed to includeor requirewhen including the files that contain your functions.

使用require_onceinclude_once与包含包含您的函数的文件相反的includerequire

The _oncesiblings of includeand requirewill force PHP to check if the file has already been included/required, and if so, not include/requireit again, thereby preventing 'cannot redeclare x function...' fatal errors.

_once的兄弟姐妹includerequire将强制PHP检查文件是否已被列入/必需的,如果是这样,不是include/require一遍,从而防止“无法重新声明X功能...”致命错误。

回答by Dooltaz

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

http://us.php.net/function_exists

http://us.php.net/function_exists

回答by smack0007

"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?

function_exists”会告诉你一个函数是否已经被声明。尽管我怀疑您可能在多次包含文件时遇到问题。当您包含文件时,您是使用 require_once 或 include_once 还是只使用 require / include?

回答by Serj Sagan

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

如果您正在处理类method_exists()可能是您正在寻找的:

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

    }
}

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

这将function_name在尝试声明之前检查当前类以确保该函数不存在