Rosso Glitterato
Sito in lingua italiana Website in English language Rosso Glitterato - Portale Informatico
Debug di una routine PHP
Di cosa si tratta

Un programmatore sa quanto può essere utile effettuare il debug di un programma per capire se funziona correttamente. A tal proposito ho costruito una semplice funzione PHP che scrive su un file di testo il valore della variabile che vogliamo tracciare

La funzione

function myDebug($var){
 
    // File debug name
    $file = "myDebug.txt";      
 
    // Open file debug
 
    if (!(file_exists($file)))
    {fopen($file,"w");}   
 
    // Variable name
    foreach($GLOBALS as $var_name => $value) {
        if ($value === $var) {
            $variableName = $var_name;
        }
    }
 
    // Debug Var
    $stringDebug = "-------------------------------------------------------------"."\n";
    $txtDebug=fopen($file,"a+");
    fwrite($txtDebug,$stringDebug);
 
    $stringDebug = "Var: ".$variableName."\n";
    $txtDebug=fopen($file,"a+");
    fwrite($txtDebug,$stringDebug);
 
    $stringDebug ="Value: ";  
 
    if (gettype($var) === 'array'){
 
        ob_start();
        var_dump($var);
        $content = ob_get_contents();
        ob_end_clean();
 
        $stringDebug .= "\n".$content."\n";
    }           
    else{
        $stringDebug .= $var."\n";
    }
 
    $txtDebug=fopen($file,"a+");
    fwrite($txtDebug,$stringDebug);
 
 
    // Close Debug
    fclose($txtDebug);
 
}

Come si usa

Supponi di voler tracciare nella tua routine PHP le variabili $a, $b, $c

$a = array("apple", "beer");
$b = "Hello";
$c = 44;
 
myDebug($a);
myDebug($b);
myDebug($c);
 

Quando esegui la routine verrà creato il file "myDebug.txt" con questo contenuto:

Rosso Glitterato, un sito di Morris C.Rosso Glitterato è un sito creato da Morris C. - 2018
Sito validato W3C per l'HTML5