当有命名空间namespace时,function_exists的传参

<?php
namespace DeepCopy;

use function function_exists;

if (false === function_exists('DeepCopy\deep_copy')) {
    /**
     * Deep copies the given value.
     *
     * @param mixed $value
     * @param bool  $useCloneMethod
     *
     * @return mixed
     */
    function deep_copy($value, $useCloneMethod = false)
    {
        return (new DeepCopy($useCloneMethod))->copy($value);
    }
}

今天看到这段代码后,一开始不知道为什么function_exists传的是DeepCopy\deep_copy,不太理解就看PHP文档吧,function_exists文档.在文档的User Contributed Notes找到了答案
It should be noted that the function_exists check is not relative to the root namespace. This means that the namespace should be appended to the check:

namespace test;

if (!function_exists(__NAMESPACE__ . '\example'))
{

    function example()
    {

    }

}
?>

然后自己写一个进行测试

<?php
namespace test;
function index()
{
    var_dump(function_exists('test'));//false
    var_dump(function_exists(__NAMESPACE__ . '\test'));//true
}
function test(){}
index();

一个false,一个true,这是因为有命名空间时,这是函数是归属在当前命名空间下的,所以需要加上命名空间才能获取到

php
本作品采用《CC 协议》,转载必须注明作者和本文链接
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!