略微加速

PHP官方手册 - 互联网笔记

PHP - Manual: 使用命名空间:后备全局函数/常量

2024-03-29

使用命名空间:后备全局函数/常量

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

在一个命名空间中,当 PHP 遇到一个非限定的类、函数或常量名称时,它使用不同的优先策略来解析该名称。类名称总是解析到当前命名空间中的名称。因此在访问系统内部或不包含在命名空间中的类名称时,必须使用完全限定名称,例如:

示例 #1 在命名空间中访问全局类

<?php
namespace A\B\C;
class 
Exception extends \Exception {}

$a = new Exception('hi'); // $a 是类 A\B\C\Exception 的一个对象
$b = new \Exception('hi'); // $b 是类 Exception 的一个对象

$c = new ArrayObject// 致命错误, 找不到 A\B\C\ArrayObject 类
?>

对于函数和常量来说,如果当前命名空间中不存在该函数或常量,PHP 会退而使用全局空间中的函数或常量。

示例 #2 命名空间中后备的全局函数/常量

<?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('hi'), "\n"// 输出 "1"
if (is_array('hi')) { // 输出 "is not array"
    
echo "is array\n";
} else {
    echo 
"is not array\n";
}
?>
add a noteadd a note

User Contributed Notes 1 note

up
26
markus at malkusch dot de
7 years ago
You can use the fallback policy to provide mocks for built-in functions like time(). You therefore have to call those functions unqualified:

<?php
namespace foo;

function
time() {
    return
1234;
}

assert (1234 == time());
?>

However there's a restriction that you have to define the mock function before the first usage in the tested class method. This is documented in Bug #68541.

You can find the mock library php-mock at GitHub.

官方地址:https://www.php.net/manual/en/language.namespaces.fallback.php

冷却塔厂家 广告
-- 广告
北京半月雨文化科技有限公司.版权所有 京ICP备12026184号-3