2012-11-30 14 views
0

我正在尝试为我的某个网站制作一个调试类,类似于Java中的记录器类。在PHP中使用常量的语法错误

<?php 

abstract class DebugLevel 
{ 
    const Notice = 1; 
    const Info = 2; 
    const Warning = 4; 
    const Fatal = 8; 
} 

class Debug 
{ 
    private static $level = DebugLevel::Fatal | DebugLevel::Warning | DebugLevel::Info | DebugLevel::Notice; 


} 

?> 

我得到一个Parse error

Parse error: syntax error, unexpected '|', expecting ',' or ';' in (script path) on line 13 

有什么不对?

回答

3

您不能将逻辑添加到PHP中的类属性(变量)或常量。

documentation

这个声明可能包括初始化,但这种 初始化必须是一个恒定值 - 也就是说,它必须能够 在编译时进行评估,不能依赖在运行时 信息为了被评估。


要设置这样的值使用__construct()功能。

class Debug { 

    public $level; // can not be a constant if you want to change it later!!! 

    public function __construct() { 
     $this->level = DebugLevel::Fatal | DebugLevel::Warning | DebugLevel::Info | DebugLevel::Notice; 
    } 

} 

或许更优雅:

class Debug { 

    public $level; // can not be a constant if you want to change it later!!! 

    public function setLevel($level) { 
     $this->level = $level; 
    } 

} 

然后你就可以调用这个:

$Debug = new Debug(); 
$Debug->setLevel(DebugLevel::Warning); 
+0

所以,我该怎么做我想要做什么? –

+0

@RiccardoBestetti:使用'__construct()'函数。我们不喜欢这里的勺子喂食器。使用'__construct()'非常简单。 –

+0

当我发布评论时,他还没有写过使用'__construct()'。 –