【发布时间】:2013-11-12 17:58:00
【问题描述】:
我正在尝试创建一个错误记录类,我有一些函数可以设置各种输出方法,例如 DB、文件、返回和屏幕。我希望将所有错误都存储到一个数组中,当调用__destruct() 时,我想阻止客户端等待数据和有关用户遇到的错误的日志详细信息。这样他们就不必向我报告错误。
我有 2 种模式,一个用于测试功能的简单 GUI,而实际脚本以 JSON 格式生成机器对机器的响应。对于 GUI,最终转储很好,但对于 JSON,它会破坏响应。所以所有错误报告都关闭了,我必须自己处理任何会在屏幕上转储的错误,因此 function flush_log($return) 中的 $return 如果设置为 true,则使函数返回一个字符串。
在报告刷新错误后我想:unset($this->log_arrays)
或为空:$this->log_arrays=Array();,但它超出了范围 - 我明白为什么,我的函数使用本地副本 - 但是如何重置数组?
[编辑]:
我试过了:
$this->log_arrays = Array();$this->log_arrays = null;-
数组弹出:
for ($i = 1; count($this->log_arrays); $i++) { array_pop($this->log_arrays); }
但我认为它们都可以起作用,因为在类函数中您使用变量的副本,因此它们基本上超出了范围。
[/EDIT]:
这是一个已经简化的类..:
<?php
class log_strings extends mysqli
{
private $log_arrays = Array();
public function __construct($output_to_file=false, $output_to_db=true, $fall_back_file=true, $arguments, $ip=null)
{
// Setup mysqli connection, file handle or report error if one or all have failed.
// Also check wich outputs should be used and keep that info for later.
}
public function log($level, $string)
{
$log_arrays[] = Array('level' => $level, 'string' => $string);
}
public function __destruct()
{
$this->flush_log();
}
public function flush_log($return=false)
{
if (!isset($log_arrays) && count($log_arrays) == 0)
{
return true;
}
if ($return)
{
return $this->return_output();
}
else
{
$success = false;
// if enabled, output to db
if ($this->output_to_db)
{
$success = $success || $this->mysqli_output();
}
// if enabled or if db failed and fallback is enabled, output to file
if ($this->output_to_file || ($this->fall_back_file && !$success))
{
$success = $success || $this->file_output();
}
// if neither file or db succeeded, dump on screen
if ($success = false)
{
$this->screen_dump();
}
return true;
}
unset($this->log_arrays); // <= This is what it is all about!
}
private function screen_dump()
{
foreach($this->log_arrays as $array)
{
echo "<strong>{$array['level']}</strong>{$array['string']}<br/>\n";
}
}
private function mysqli_output()
{
// Output to db functionally equal to $this->screen_dump()
}
private function file_output()
{
// Output to file functionally equal to $this->screen_dump()
}
private function return_output()
{
// Return output functionally equal to $this->screen_dump()
}
}
?>
【问题讨论】:
标签: php class object scope unset