“Notice: Undefined variable”, “Notice: Undefined index”, and “Notice: Undefined offset” using PHP

后端 未结 28 946
盖世英雄少女心
盖世英雄少女心 2021-01-24 14:18

I\'m running a PHP script and continue to receive errors like:

Notice: Undefined variable: my_variable_name in C:\\wamp\\www\\mypath\\index.php on line 10

28条回答
  •  余生分开走
    2021-01-24 14:37

    I use all time own useful function exst() which automatically declare variables.

    Your code will be -

    $greeting = "Hello, ".exst($user_name, 'Visitor')." from ".exst($user_location);
    
    
    /** 
     * Function exst() - Checks if the variable has been set 
     * (copy/paste it in any place of your code)
     * 
     * If the variable is set and not empty returns the variable (no transformation)
     * If the variable is not set or empty, returns the $default value
     *
     * @param  mixed $var
     * @param  mixed $default
     * 
     * @return mixed 
     */
    
    function exst( & $var, $default = "")
    {
        $t = "";
        if ( !isset($var)  || !$var ) {
            if (isset($default) && $default != "") $t = $default;
        }
        else  {  
            $t = $var;
        }
        if (is_string($t)) $t = trim($t);
        return $t;
    }
    

提交回复
热议问题