简体   繁体   中英

Is a global PHP CONSTANT available inside of a Class file?

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

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, eg

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.

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 ....
}

You can't use expression (.) in field initializer. See example one in PHP manual

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM