简体   繁体   English

PHP - 从变量到常量的值

[英]PHP - value from variable to constant

I'm learning OOP in PHP and I want to put value from variable to class constant. 我正在学习PHP中的OOP,我希望将值从变量赋值给类常量。 How can I do that? 我怎样才能做到这一点?

This is my code (not working!): 这是我的代码(不工作!):

class Dir {

const ROOT = $_SERVER['DOCUMENT_ROOT']."project/";

function __construct() {

}
}

Is there any solution, how to take value from variable, add string and put it to constant - in OOP? 有没有解决方案,如何从变量中获取值,添加字符串并将其置于常量 - 在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. 

Constant can't have variables. 常量不能有变量。

I suggest you not to depend on $_SERVER['DOCUMENT_ROOT'] , instead, you could define the ROOT your self. 我建议你不要依赖$_SERVER['DOCUMENT_ROOT'] ,相反,你可以定义自己的ROOT

For example, you have a config.php in the document root, you could do 例如,您可以在文档根目录中使用config.php

define('ROOT', __DIR__.'/'); // php version >= 5.3
define('ROOT', dirname(__FILE__).'/'); // php version < 5.3

then use the ROOT instead. 然后使用ROOT代替。

Why not set it in your __construct() . 为什么不在__construct()设置它。 Technically, that's what it is there for. 从技术上讲,这就是它的用途。

class Dir {

    public function __construct() {
        self::ROOT = $_SERVER['DOCUMENT_ROOT']."project/";
    }
}

I suggest you this solution because you want to use OOP and all have to be inside the class. 我建议你这个解决方案,因为你想使用OOP,所有都必须在课堂内。 So because a const or static var direct use is not possible I would use a static function: 因为不能使用const或static var直接使用我会使用静态函数:

class Dir
{
    public static function getRoot()
    {
        return $_SERVER['DOCUMENT_ROOT'] . 'project/';
    }
}

and you can use it like 你可以像使用它一样

Dir::getRoot();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM