Home  >  Article  >  Backend Development  >  php fallback global functions/constants

php fallback global functions/constants

伊谢尔伦
伊谢尔伦Original
2016-11-23 10:49:29875browse

In a namespace, when PHP encounters an unqualified class, function, or constant name, it uses a different precedence strategy to resolve the name. Class names always resolve to names in the current namespace. Therefore, when accessing class names internal to the system or not contained in the namespace, you must use fully qualified names, such as:

Example #1 Accessing global classes in the namespace

<?php
    namespace A\B\C;
    class Exception extends \Exception {}
    $a = new Exception(&#39;hi&#39;); // $a 是类 A\B\C\Exception 的一个对象
    $b = new \Exception(&#39;hi&#39;); // $b 是类 Exception 的一个对象
    $c = new ArrayObject; // 致命错误, 找不到 A\B\C\ArrayObject 类
?>

For functions and constants, if the current name If the function or constant does not exist in the space, PHP will fall back to using the function or constant in the global space.

Example #2 Backed global functions/constants in namespace

<?php
    namespace A\B\C;
    const E_ERROR = 45;
    function strlen($str)
    {
        return \strlen($str) - 1;
    }
    echo E_ERROR, "\n"; // 输出 "45"
    echo INI_ALL, "\n"; // 输出 "7" - 使用全局常量 INI_ALL
    echo strlen(&#39;hi&#39;), "\n"; // 输出 "1"
    if (is_array(&#39;hi&#39;)) { // 输出 "is not array"
        echo "is array\n";
    } else {
        echo "is not array\n";
    }
?>


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn