Is global php CONSTANT available inside a class file?

Is global PHP CONSTANT available inside a class file?

define('SITE_PATH', 'C:/webserver/htdocs/somefolder/'); 

Then in my class file I will try

 public $debug_file = SITE_PATH. 'debug/debug.sql'; 

This does not seem to work,

Parse error: parse error, pending ','' or '; ' 'in C: \ WebServer \ HTDOCS \ SomeFolder \ includes \ classes \ Database.class.php on line 21

+4
source share
4 answers

You cannot have an expression in a class declaration.

I would suggest passing the path to:

 public function __construct($path) { $this->debug_path = $path; } 

This gives you more flexibility, if you ever want to change the path, you do not need to change the constant, just what you go through.

Or you can create several objects, all of which have different paths. This is useful if it is an autoloader class, as you might want to load multiple directories.

 $autoloader = new Autoload(dirname(SYS_PATH)); $autoloader->register_loader(); class Autoload { public $include_path = ""; public function __construct($include_path="") { // Set the Include Path // TODO: Sanitize Include Path (Remove Trailing Slash) if(!empty($include_path)) { $this->include_path = $include_path; } else { $this->include_path = get_include_path(); } // Check the directory exists. if(!file_exists($this->include_path)) { throw new Exception("Bad Include Path Given"); } } // .... more stuff .... } 
+3
source

I am the second that others have said. Since $ debugFile seems like an optional dependency, I would suggest initializing the normal default when creating the class, and then allowing it to change by setting the injector when necessary, for example.

 define('SITE_PATH', 'C:/webserver/htdocs/somefolder/'); class Klass { protected $_debugFile; public function __construct() { $this->_debugFile = SITE_PATH. 'debug/debug.sql' // default } public function setDebugFile($path) { $this->_debugFile = $path // custom } } 

Note that injecting SITE_PATH instead of hard coding would be even better practice.

+4
source

You cannot use expression (.) In a field initializer. See an example in the PHP manual

+2
source

Yes, however, property values ​​defined at compile time cannot be expressions.

See http://php.net/manual/en/language.oop5.static.php

0
source

All Articles