我正在學習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