Tak zkus neco jednoducheho, treba jen zapis chybovych stavu do souboru. Ten kod je trochu slozitejsi, ale treba to pochopis. Rozdil proti klasickym funkcim je jen v tom, ze je vsechno obalene do jedne promenne. Coz je soucasne vyhoda, protoze pak pri kopirovani nemuzes zapomenout na cast kodu. Ale musis se zbavit takoych zlozvyku jako global a nebo global pouzit nejlepe pro celou class, abys pak u podfunkci nemusel dohledavat, ktere veci z vnejsku treba jeste prikopirovat.
<?php
class ClassLog
{
private $cl_file = null;
private $cfg = null;
public $err;
public $data;
function __construct($filename)
{
$cfg = array(
'filename' => $filename,
'filetimeout' => 5000
);
$this->cfg = $cfg;
$this->err = array();
$this->data = array();
}
function __destruct()
{
//$this->write();
}
public function add($str)
{
$str = trim($str);
if ($str!=="")
{
$this->data[] = date("Y-m-d H:i:s",time()) . " " . $str;
$this->write();
}
}
public function write()
{
$str = implode("\n",$this->data)."\n";
echo nl2br($str);
$this->writeFile($this->cfg['filename'],$str,$this->cfg['filetimeout'],'a');
$this->data = array();
}
public function writeFile($_file_name,$_data_to_save,$_end_time=5000,$_type='w',$_mod='0755')
{
$old = umask(0); // prava precti
@chmod($_file_name,$_mod); // prava nastav
$fp = fopen($_file_name,$_type); // file pointer | handle
if ($fp)
{
$start_time = microtime();
do {
$can_write = flock($fp, LOCK_EX);
if (!$can_write)
{usleep(round(rand(0,100)*1000));}
}
while ((!$can_write) and ((microtime() - $start_time) < $_end_time));
if ($can_write)
{fputs($fp,$_data_to_save);} // zapis
else {$this->err[] = 'writeFile|file_not_written|'.$_file_name; return false;}
fclose($fp);
umask($old); // prava vrat
}
else {$this->err[] = 'writeFile|file_not_open|'.$_file_name; return false;}
return true;
}
};
$log = new ClassLog('soubor.txt');
$log->add('chybova hlaska');
$log->add('dalsi chybova hlaska');
?>
Hlavne se to da pak pouzit pro vice veci naraz. Treba, kdyz pouzivas 2 ruzna pripojeni k sql, tak si je zapises jako
$sql1 = new ClassSql('server','jmeno','heslo','db');
$sql2 = new ClassSql('server','jmeno','heslo','db');
A pak pouzivas jako
$sql1->query('...');
$sql2->query('...');
Coz je velmi fajn, ze je konstrukce stejna.