Search code examples
phpstatic

Static array in PHP function not working


PHP - Testing a simple function with a static array variable. I assume the static variable declared in the function would make it available outside of the function.

This function just takes a message and adds it to the errors[] array, and then be able to use this list of errors[] outside the function.

I get the error message: "Notice: Undefined variable: errors in....on line 10"

Line 10 has the code, "print_r($errors);"

function addErrors($errmessage){
    static $errors = array();
    $errors[] = $errmessage; 
}
addErrors('test1');
addErrors('test2');
print_r($errors);

Your input is appreciated!


Solution

  • $errors is a static variable inside the function, you cannot access it from the global scope.

    here's an example how to achieve what you are trying to do :

    PHP 7 < :

    <?php
    
    /**
    * @param string|null the error message to add or null
    * @return array|null returns all errors if provided with null 
    */
    function errors($error = null) {
       static $errors = [];
       if($error !== null) {
           $errors[] = $error;
           return null;
       } else {
           return $errors;
       }
    }
    
    errors('Error !');
    errors('Another !');
    print_r(errors());
    

    PHP 7 >= :

    <?php
    
    function errors(string $error = null): ?array {
       static $errors = [];
       if($error !== null) {
           $errors[] = $error;
           return null;
       } else {
           return $errors;
       }
    }
    
    errors('Error !');
    errors('Another !');
    print_r(errors());