PHP - value from variable to constant

2019-07-21 15:00发布

I'm learning OOP in PHP and I want to put value from variable to class constant. 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?

4条回答
疯言疯语
2楼-- · 2019-07-21 15:14

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/";
    }
}
查看更多
别忘想泡老子
3楼-- · 2019-07-21 15:18

I suggest you this solution because you want to use OOP and all have to be inside the class. So because a const or static var direct use is not possible I would use a static function:

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

and you can use it like

Dir::getRoot();
查看更多
叛逆
4楼-- · 2019-07-21 15:21

Constant can't have variables.

I suggest you not to depend on $_SERVER['DOCUMENT_ROOT'], instead, you could define the ROOT your self.

For example, you have a config.php in the document root, you could do

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

then use the ROOT instead.

查看更多
小情绪 Triste *
5楼-- · 2019-07-21 15:34

From the manual page http://www.php.net/manual/en/language.oop5.constants.php you can find that:

The value must be a constant expression, not (for example) a variable, a property, a result of a mathematical operation, or a function call. 
查看更多
登录 后发表回答