declare constant passing variable inside object

1

I need to call the root directory of my project, just the root regardless of where the script is.

Finding $_SERVER['DOCUMENT_ROOT'] and good practice I want to pass this to a constant within an object using const .

<?php
class Test{
   const DIROOT = $_SERVER['DOCUMENT_ROOT'];
}

However, I get the following error:

  

"Fatal error: Constant expression contains invalid operations in   /var/www/html/sys/php/test.php on line 3 "

If I try to declare it with pure string const DIROOT = "/exemplo"; it works. Why?

    
asked by anonymous 19.08.2017 / 00:46

1 answer

3

I did not understand the question of "good practice", but the error occurs because it is not possible to initialize constants with any value other than a constant expression. See documentation :

  

The value must be a constant expression, and can not be (for example) a variable, a property, or a function call.

The constant expression is just a value, as in:

const DIROOT = "/exemplo";

Or even an expression with constant values, it's like:

const PI = 3 + 0.14159;

Or with strings :

const NAME = "Foo" . "Bar";

That is, you can not assign a variable:

const DIROOT = $_REQUEST["DOCUMENT_ROOT"]; // erro

Or a function call:

const DIROOT = get_dir_root(); // erro

However, using define you can do something similar to what you want:

define("DIROOT", $_REQUEST["DOCUMENT_ROOT"]);

If this is really necessary for your application.

    
19.08.2017 / 01:00