【发布时间】:2011-05-15 21:09:24
【问题描述】:
我正在学习 OO PHP,并且正在尝试直接掌握一些编码实践。这是我用于错误(和异常)处理的一些代码的精简版本:
final class MyErrorExceptionHandler {
private $level = array(); // error levels to be handled as standard errors
private $path = array(); // full path to file
private $path_short; // filename plus working dir
public function myErrorHandler($severity, $message, $file, $line) {
if (error_reporting() & $severity) { // error code is included in error_reporting
$this->level = array(E_WARNING => 'warning',
E_NOTICE => 'notice',
E_USER_WARNING => 'user warning',
E_USER_NOTICE => 'user notice');
if (array_key_exists($severity, $this->level)) { // handle as standard error
/*$this->severity = $severity;
$this->message = $message;
$this->file = $file;
$this->line = $line;*/
$this->printMessage($severity, $message, $file, $line);
} else { // fatal: E_USER_ERROR or E_RECOVERABLE_ERROR use php's ErrorException converter
throw new ErrorException($message, 0, $severity, $file, $line);
}
}
} // fn myErrorHandler
private function printMessage($severity, $message, $file, $line) {
echo ucfirst($this->level[$severity]) . ': ' . $message;
$this->shortenPath($file);
echo ' in ' . $this->path_short . ' on line ' . $line;
} // fn printMessage
private function shortenPath($file) {
$this->path_short = $file;
$this->path = explode(DIRECTORY_SEPARATOR, $file);
if (count($this->path) > 2) { // shorten path to one dir, if more than one dir
$this->path_short = array_pop($this->path); // filename
$this->path_short = end($this->path) . DIRECTORY_SEPARATOR . $this->path_short; // dir+file
}
} // fn shortenPath
} // cl MyErrorExceptionHandler
这个问题的标题可能有点偏离,因为我不是 100% 了解术语。基本上我想弄清楚一些事情。
- 将
$level和$path显式声明为数组是否正确? - 是否应按原样声明
$level(并设为$this->level)?如果是这样,我是否在明智的地方分配了它的值(E_WARNING等)?构造函数(此处未显示)会是更明智的选择吗? - 注意
myErrorHandler()中的注释块。最初我在类的顶部声明了所有这些属性,然后在没有任何参数的情况下调用$this->printMessage()。哪种方法更正确?如果我保持代码不变,我是否想在printMessage()中使用$this->severity = $severity等? - 那么,最好是:
替换
$this->shortenPath($file);
echo ' in ' . $this->path_short . ' on line ' . $line;
与
$path_short = $this->shortenPath($file);
echo ' in ' . $path_short . ' on line ' . $line;
最后,并在shortenPath()中给出返回值?
我意识到这是几个不同问题的混搭,但我想要了解的是关于声明/使用变量/属性的正确样式的常见问题,特别是在处理方法时。
总结一下:什么时候应该使用$this->foo = $foo?
【问题讨论】:
标签: php parameters this declaration