Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/230.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
类文件中是否有全局PHP常量?_Php_Constants - Fatal编程技术网

类文件中是否有全局PHP常量?

类文件中是否有全局PHP常量?,php,constants,Php,Constants,类文件中是否有全局PHP常量 define('SITE_PATH', 'C:/webserver/htdocs/somefolder/'); 然后在我的类文件中我尝试了这个 public $debug_file = SITE_PATH. 'debug/debug.sql'; 但这似乎不起作用 分析错误:分析错误,应为 “”、”或“/code>”;”在里面 C:\webserver\htdocs\somefolder\includes\classes\Database.class.php 在线

类文件中是否有全局PHP常量

define('SITE_PATH', 'C:/webserver/htdocs/somefolder/');
然后在我的类文件中我尝试了这个

public $debug_file = SITE_PATH. 'debug/debug.sql';
但这似乎不起作用

分析错误:分析错误,应为 “
”、”或“/code>”;”在里面
C:\webserver\htdocs\somefolder\includes\classes\Database.class.php
在线21


是的,但是,在编译时定义的属性值不能是表达式


请参见

您不能在字段初始值设定项中使用表达式(.)

类声明中不能有表达式

我建议将这条路穿过:

public function __construct($path)
{
    $this->debug_path = $path;
}
这为您提供了更大的灵活性,如果您想要更改路径,您不必更改常量,只需更改传入的内容

或者可以创建多个具有不同路径的对象。如果它是一个自动加载程序类,这将非常有用,因为您可能希望让它加载多个目录

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

我赞同别人说的话。由于$debugFile似乎是一个可选的依赖项,我建议在创建类时初始化一个sane默认值,然后在需要时允许通过setter注入进行更改,例如

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

注意,注入SITE_PATH,而不是硬编码,将是更好的做法。

我明白了,所以我应该用调试文件的完整路径创建另一个新常量。。你可以。。它只需要包含文本字符串。是的,@Jasondavis。但您可以在类初始化时向它传递一个路径。这将允许您使用多个路径(多个对象)或稍后更改路径。注释意味着我从我的项目中为您提供了源代码,而不是重新创建它。耶!get_include_path()可以返回由操作系统特定路径分隔符分隔的多个路径。因此,如果定义了多个路径,但分别是有效路径,那么对文件_exists的调用将失败。