我正在学习OO PHP,并试图直接获得一些编码实践。下面是一些代码,我使用了错误(和除外)削减版本处理:方法中的所有变量都需要是对象属性吗? (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
?
谢谢!不过,我想知道这个问题:“如果你需要多个方法中的任何属性,那么建议你将该属性赋值给你的对象。如果printMessage()是使用这些属性的唯一方法,那么no。”拿,例如,$文件。它从myErrorHandler(),printMessage()到shortenPath()。这些都可以用一种方法,但我为了可读性/实用性而将其分解。所以是的,这不仅仅是一种方法,但是$文件只会经过这个链。对于Exceptions我有一个很长的方法,我没有在这里包含,也没有涉及到$ file。 – CartoonChess 2010-11-25 19:55:58