直接上代码:
hello.php:
<?php
const name = 'hello.php/name';
?>
index.php:
namespace mine;
const name = 'index.php/name';
include './hello.php';
echo constant('name'),PHP_EOL; //输出 hello.php/name
echo name; //输出 index.php/name

问题:我在index.php中引入了hello.php,目的是为了测试命名空间。但是最后两种方式访问常量的结果却是不同的,求助一下各位~
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
常量也是受到命名空间影响的, 你的hello.php里面的常量实际上是
\name, index.php 里面的实际上是\mine\name这样看,echo之前,先看一下所有定义的常量
name常量对应的值是"hello.php/name",因为第二个页面定义了命名空间,所以变量的访问就带上了命名空间,正如@vimac所说。
所以echo name 其实是 echo mine\name ,同理 echo contant("mine\name") 才是 "index.php/name"