命名空间内部的常量说明

命名空间内部的常量说明

本文介绍了php define()命名空间内部的常量说明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正如标题所述,我真的很想澄清这一点.我已经在此处阅读了有关该主题的几篇文章和帖子,但有些东西对我来说并不是单击.我会补充说,我对Php有点陌生.好,这就是我要了解的内容;

As the title states, I would really like to clarify this. I have read a few articles and postings here on this topic, something just isn't clicking for me. I'll add I'm a bit new to Php. OK, here's what I want to understand;

namespace Information;
define('ROOT_URL', 'information/');
define('OFFERS_URL', ROOT_URL . 'offers/');

namespace Products;
define('ROOT_URL', 'products/');
define('OFFERS_URL', ROOT_URL . 'offers/');

我希望常量是可构造的,即从基本常量构建常量,这就是为什么我使用define('NAME', value );.

I want the constants to be constructable, ie, build constants from base constant(s), that's why I'm using define('NAME', value);.

我的问题是,ROOT_URL的值会产生相对于其名称空间的值吗?像这样;

My question being, will the value of ROOT_URL yield the value relative to its' namespace? Like this;

$info_offers_url = \Information\OFFERS_URL;  ('information/offers/')
$prod_offers_url = \Products\OFFERS_URL;     ('products/offers/')

或者是否define();将ROOT_URL放在全球范围内,因此我不应该这样做吗?有更好的做法吗?

Or does define(); place ROOT_URL in a global scope, hence I shouldn't do this? Is there a better practice?

非常感谢所有帮助.

推荐答案

如果要在名称空间中定义常量,则即使在调用define时,也需要在调用define()时指定名称空间. ()来自命名空间.我尝试过的以下示例将使其清楚.

If you want to define a constant in a namespace, you will need to specify the namespace in your call to define(), even if you're calling define() from within a namespace. The following examples which I tried will make it clear.

以下代码将在全局名称空间(即"\ CONSTANTA")中定义常量"CONSTANTA".

The following code will define the constant "CONSTANTA" in the global namespace (i.e. "\CONSTANTA").

<?php
namespace mynamespace;
define('CONSTANTA', 'Hello A!');
?>

如果要为名称空间定义常量,可以像

if you want to define constant for a namespace you can define like

<?php
namespace test;
define('test\HELLO', 'Hello world!');
define(__NAMESPACE__ . '\GOODBYE', 'Goodbye cruel world!');
?>

否则,您可以使用const在当前名称空间中定义一个常量:

Otherwise, you can use const to define a constant in the current namespace:

<?php

namespace NS;

define('C', "I am a constant");
const A = "I am a letter";

echo __NAMESPACE__, , PHP_EOL; // NS
echo namespace\A, PHP_EOL; // I am a letter
echo namespace\C, PHP_EOL; // PHP Fatal error:  Uncaught Error: Undefined constant 'NS\C'

摘录自手册

这篇关于php define()命名空间内部的常量说明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 20:35