【发布时间】:2010-12-04 03:54:42
【问题描述】:
如何检查函数my_function是否已经存在于PHP中?
【问题讨论】:
如何检查函数my_function是否已经存在于PHP中?
【问题讨论】:
if(function_exists('my_function')){
// my_function is defined
}
【讨论】:
is_callable,因为这个答案是 Google 上的最高结果。
function_exists"
$date = new DateTime(); $date->getTimestamp() ?
http://php.net/manual/en/function.function-exists.php
<?php
if (!function_exists('myfunction')) {
function myfunction()
{
//write function statements
}
}
?>
【讨论】:
如果my_function 在命名空间中:
namespace MyProject;
function my_function() {
return 123;
}
你可以检查它是否存在
function_exists( __NAMESPACE__ . '\my_function' );
在同一个命名空间中或
function_exists( '\MyProject\my_function' );
在命名空间之外。
附:我知道这是一个非常古老的问题,并且 PHP 文档从那时起改进了很多,但我相信人们仍然在这里偷看,这可能会有所帮助。
【讨论】:
var_dump( get_defined_functions() );
显示所有现有功能
【讨论】:
我想指出 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() {}
如果您想防止致命错误并仅在尚未定义的情况下定义函数,则需要执行以下操作:
<?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() {}
}
【讨论】:
检查多个 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
【讨论】: