在类文件中可以使用全局PHP CONSTANT吗? [英] Is a global PHP CONSTANT available inside of a Class file?

查看:63
本文介绍了在类文件中可以使用全局PHP CONSTANT吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在类文件中可以使用全局PHP CONSTANT吗?

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';

这似乎不起作用,

解析错误:解析错误,期望
',''或';''在
C:\ \webserver\htdocs\somefolder\包括\类\Database.class.php
在第21行

Parse error: parse error, expecting ','' or';'' in C:\webserver\htdocs\somefolder\includes\classes\Database.class.php on line 21


推荐答案

在类声明中不能有表达式。

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.

或者您可以创建多个具有不同路径的对象。如果它是一个autoloader类,这很有用,因为您可能希望它加载多个目录。

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

这篇关于在类文件中可以使用全局PHP CONSTANT吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆