在 PHP 中,如何检查函数是否存在?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4351835/
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
In PHP, how do I check if a function exists?
提问by bradg
How can I check if the function my_function
already exists in PHP?
如何检查该函数是否my_function
已存在于 PHP 中?
回答by Mark Elliot
Using function_exists
:
if(function_exists('my_function')){
// my_function is defined
}
回答by Avinash Saini
http://php.net/manual/en/function.function-exists.php
http://php.net/manual/en/function.function-exists.php
<?php
if (!function_exists('myfunction')) {
function myfunction()
{
//write function statements
}
}
?>
回答by T.Todua
var_dump( get_defined_functions() );
DISPLAYS all existing functions
显示所有现有功能
回答by SeanDowney
I want to point out what kitchinhas pointed out on php.net:
我想指出kitchin在 php.net 上指出的内容:
<?php
// This will print "foo defined"
if (function_exists('foo')) {
print "foo defined";
} else {
print "foo not defined";
}
//note even though the function is defined here, it previously was told to have already existed
function foo() {}
If you want to prevent a fatal error and define a function only if it has not been defined, you need to do the following:
如果要防止致命错误并仅在未定义的情况下定义函数,则需要执行以下操作:
<?php
// This will print "defining bar" and will define the function bar
if (function_exists('bar')) {
print "bar defined";
} else {
print "defining bar";
function bar() {}
}
回答by Ram Pukar
Checking Multiple function_exists
检查多个 function_exists
$arrFun = array('fun1','fun2','fun3');
if(is_array($arrFun)){
$arrMsg = array();
foreach ($arrFun as $key => $value) {
if(!function_exists($value)){
$arrMsg[] = $value;
}
}
foreach ($arrMsg as $key => $value) {
echo "{$value} function does not exist <br/>";
}
}
function fun1(){
}
Output
fun2 function does not exist
fun3 function does not exist
回答by Avag Sargsyan
And if my_function
is in namespace:
如果my_function
在命名空间中:
namespace MyProject;
function my_function() {
return 123;
}
You can check if it exists
你可以检查它是否存在
function_exists( __NAMESPACE__ . '\my_function' );
in the same namespace or
在相同的命名空间或
function_exists( '\MyProject\my_function' );
outside of the namespace.
在命名空间之外。
P.S. I know this is a very old question and PHP documentation improved a lot since then, but I believe people still taking a peek here, and this might be helpful.
PS 我知道这是一个非常古老的问题,从那时起 PHP 文档得到了很大改进,但我相信人们仍然在这里偷看,这可能会有所帮助。