开发者

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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜