php fallback global functions/constants

伊谢尔伦
Release: 2016-11-23 10:49:29
Original
874 people have browsed it

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 类
?>
Copy after login

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";
    }
?>
Copy after login


Related labels:
php
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!