declare variable passing constant inside the object

Asked

Viewed 598 times

1

I need to call the root directory of my project, only the root independent of where the script is.

Researching I found the $_SERVER['DOCUMENT_ROOT'] and as 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"; works. Why ?

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. Vide documentation:

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

The constant expression is only a value, as in:

const DIROOT = "/exemplo";

Or even an expression with constant values, ta como:

const PI = 3 + 0.14159;

Or with strings:

const NAME = "Foo" . "Bar";

That is, it is not possible to 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.

  • But the function define() can only be inside methods on the object like __construct(). Proceeding ?

  • Yes, but it makes no sense to call her inside the class. In this case it would be global.

  • define() may be anywhere, but it is used for global constants.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.