gpt4 book ai didi

php - 命名空间常量和用途

转载 作者:可可西里 更新时间:2023-11-01 13:41:27 24 4
gpt4 key购买 nike

我在使用 namespace 中的常量时遇到了一些问题。如果我定义常量并尝试按原样使用,PHP 似乎无法找到它。例如,在我的常量文件中,我的代码如下:

namespace \my\namespace\for\constants;

const DS = DIRECTORY_SEPARATOR;

然后在我的消费文件中:

namespace \some\other\namespace;

use \my\namespace\for\constants\DS as DS;

echo (realpath (DS . 'usr' . DS 'local'));

但是,我没有像预期的那样回显“/usr/local”,而是收到以下通知和一个空字符串。

Notice: Use of undefined constant DS - assumed 'DS'

如果我按如下方式更改代码:

use \my\namespace\for\constants as cns;

echo (realpath (cns\DS . 'usr' . cns\DS 'local'));

我得到了预期的结果,但它显然比直接将常量拉入要方便得多。

你可以在命名空间中为类/接口(interface)/特征起别名,难道你不能给常量起别名吗?如果你能做到,那么怎么做?

最佳答案

PHP 5.6 添加了对从命名空间导入函数和常量的支持:

namespace my\space;

const CONSTANT_NAME = 123;

function function_name() {
echo "Test\n";
}

// elsewhere:
use function my\space\function_name;
function_name();

use function my\space\function_name as f;
f();

use const my\space\CONSTANT_NAME;
echo CONSTANT_NAME . "\n";

use const my\space\CONSTANT_NAME as C;
echo C . "\n";

请注意,为了可导入,必须使用 const 而不是 define 定义常量:

namespace my\space;

const CONSTANT_NAME = 123; // this can be imported
define('CONSTANT_NAME', 123); // this sets a global constant

值得注意的是,不能导入类常量:

namespace my\space;

class Test {
const CONSTANT_NAME = 123;
}

use const my\space\Test\CONSTANT_NAME; // undefined constant
use const my\space\Test::CONSTANT_NAME; // syntax error

关于php - 命名空间常量和用途,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19740621/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com