2010-01-17 18 views
4

是一个全局PHP CONSTANT在类文件中可用吗?Class文件中是否提供全局PHP CONSTANT?

define('SITE_PATH', 'C:/webserver/htdocs/somefolder/'); 

然后在我的类文件我试试这个

public $debug_file = SITE_PATH. 'debug/debug.sql'; 

这似乎并没有工作,虽然,

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

回答

3

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

我建议传递路径:

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

这些评论意味着我从我的项目给你的源代码而不是重新创建它。好极了! – 2010-01-17 22:52:13

+0

好东西,谢谢 – JasonDavis 2010-01-17 22:58:41

+0

get_include_path()可以返回由OS特定的路径分隔符分隔的多个路径。因此,如果定义了多个路径,那么对file_exists的调用将失败,但是单独使用有效路径。 – 2010-01-17 23:07:43

2

不能使用表达式(。)在现场初始化。 See example one in PHP manual

+0

我明白了,所以我应该基本上用我的调试文件的完整路径创建另一个新常量? – JasonDavis 2010-01-17 22:46:19

+0

那么..你可以......它只需要包含文字字符串。 – 2010-01-17 22:46:39

+0

和@Jasondavis,是的。但是,您可以在初始化类时将它传递给路径。这将允许您使用多个路径(多个对象)或稍后更改路径。 – 2010-01-17 22:47:57

4

其次我说别人说什么。由于$ debugFile似乎是一个可选的依赖项,所以我建议在创建类时初始化一个默认的默认值,然后允许在需要时通过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而不是硬编码它将是更好的做法。