我正在学习 PHP 中的 OOP,我想将值从变量放入类常量。我怎样才能做到这一点?
这是我的代码(不工作!):
class Dir {
const ROOT = $_SERVER['DOCUMENT_ROOT']."project/";
function __construct() {
}
}
是否有任何解决方案,如何从变量中获取值,添加字符串并将其放入常量 - 在 OOP 中?
从手册页http://www.php.net/manual/en/language.oop5.constants.php您可以找到:
The value must be a constant expression, not (for example) a variable, a property, a result of a mathematical operation, or a function call.
常量不能有变量。
我建议你不要依赖$_SERVER['DOCUMENT_ROOT']
,相反,你可以定义ROOT
你自己。
例如,您config.php
在文档根目录中有一个,您可以这样做
define('ROOT', __DIR__.'/'); // php version >= 5.3
define('ROOT', dirname(__FILE__).'/'); // php version < 5.3
然后ROOT
改用。
Why not set it in your __construct()
. Technically, that's what it is there for.
class Dir {
public function __construct() {
self::ROOT = $_SERVER['DOCUMENT_ROOT']."project/";
}
}
我建议您使用此解决方案,因为您想使用 OOP 并且所有人都必须在课堂内。因此,由于无法直接使用 const 或 static var,我将使用静态函数:
class Dir
{
public static function getRoot()
{
return $_SERVER['DOCUMENT_ROOT'] . 'project/';
}
}
你可以像这样使用它
Dir::getRoot();