2009-06-08 85 views

回答

0

只需使用常量的名称。

echo "Root path is " . __ROOT_PATH__; 
11

功能define()是为全局常量,所以你只需要使用字符串__ROOT_PATH__(我会建议使用另一种命名方案,但。常量开始以两个下划线是由PHP保留给自己magic constants

define('__ROOT_PATH__', 'Constant String'); 
echo __ROOT_PATH__; 

如果要声明一个类常量,使用const keyword

class Test { 
    const ROOT_PATH = 'Constant string'; 
} 
echo Test::ROOT_PATH; 

虽然有一个问题:在解析脚本时评估类常量,所以不能在这些常量中使用其他变量(所以你的例子不起作用)。使用define()工程,因为它像任何其他函数一样处理,并且可以动态定义常量值。

编辑

由于PCheese指出的那样,你可以使用关键字self从类中访问,而不是类名类的常量,:

class Test { 
    const ROOT_PATH = 'Constant string'; 
    public function foo() { 
     echo self::ROOT_PATH; 
    } 
} 
# You must use the class' name outside its scope: 
echo Test::ROOT_PATH; 
+0

我认为我更喜欢你的答案,它更简洁:我只是简单地在Test类的函数中添加,你可以使用`self :: ROOT_PATH`引用常量 – PCheese 2009-06-08 06:29:46

3

使用define将定义常量全球范围内,所以只是指它直接在您的代码:

echo __ROOT_PATH__; 

如果您想将常量范围限定到某个类,则需要以不同的方式声明它。但是,该语法不会像上面那样动态声明它,使用$_SERVER

<?php 
class MyClass { 
    const MY_CONST = "foo"; 
    public function showConstant() { 
     echo self::MY_CONST; 
    } 
} 

// Example: 
echo MyClass::MY_CONST; 
$c = new MyClass(); 
$c->showConstant();