我喜欢
define("__ROOT_PATH__", "http://{$_SERVER['HTTP_HOST']}/admin");
在课堂上。我如何从函数中调用它是否带有cologn?我尝试在谷歌上查找但没有。
感谢
答案 0 :(得分:11)
函数define()
适用于全局常量,因此您只需使用字符串__ROOT_PATH__
(我建议使用另一种命名方案。以两个下划线开头的常量由PHP保留为{ {3}})
define('__ROOT_PATH__', 'Constant String');
echo __ROOT_PATH__;
如果要声明类常量,请使用magic constants:
class Test {
const ROOT_PATH = 'Constant string';
}
echo Test::ROOT_PATH;
但是有一个问题:在解析脚本时会评估类常量,因此您不能在这些常量中使用其他变量(因此您的示例将不起作用)。使用define()
有效,因为它被视为任何其他函数,并且可以动态定义常量值。
修改强>:
正如const keyword指出的那样,您可以使用关键字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;
答案 1 :(得分: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();
。
{{1}}
答案 2 :(得分:0)
只需使用常量的名称。
即
echo "Root path is " . __ROOT_PATH__;