Reputation: 48933
Is a global PHP CONSTANT available inside of a Class file?
define('SITE_PATH', 'C:/webserver/htdocs/somefolder/');
Then in my class file I try this
public $debug_file = SITE_PATH. 'debug/debug.sql';
This does not seem to work though,
Parse error: parse error, expecting
','' or
';'' in C:\webserver\htdocs\somefolder\includes\classes\Database.class.php on line 21
Upvotes: 4
Views: 4268
Reputation: 316959
I second what the others said. Since $debugFile seems an optional dependency, I'd suggest to initialize a sane default on creation of the class and then allow changing it by setter injection when needed, e.g.
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 hardcoding it, would be even better practice.
Upvotes: 5
Reputation: 61557
You cannot have an expression in a class declaration.
I would suggest passing the path in:
public function __construct($path)
{
$this->debug_path = $path;
}
This gives you more flexibility if you ever want to change the path, you don't have to change a constant, just what you pass in.
Or you could create multiple objects that all have different paths. This is useful if it is an autoloader class, as you might want to have it 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 ....
}
Upvotes: 3
Reputation: 7478
You can't use expression (.) in field initializer. See example one in PHP manual
Upvotes: 2
Reputation: 3930
Yes, however, property values defined at compile time cannot be expressions.
See http://php.net/manual/en/language.oop5.static.php
Upvotes: 0