Undefined variable problem with PHP function

前端 未结 5 1937
隐瞒了意图╮
隐瞒了意图╮ 2020-11-27 08:06

I\'m a PHP newbie, so I have a minor problem functions. I have this line of code:



        
相关标签:
5条回答
  • 2020-11-27 08:25

    You can't use $pera inside the method like that because it's not defined inside the method scope.

    If you want to use the method, pass it as a parameter.

    function provera($prom, $pera){ //passed as a param
        if (preg_match("/[0-9\,\.\?\>\.<\"\'\:\;\[\]\}\{\/\!\\\@\#\$\%\^\&\*\(\)\-    \_\=\+\`[:space:]]/",$prom)){
            echo "Nepravilan unos imena ili prezimina!";
        echo $pera;
    }
    
    0 讨论(0)
  • 2020-11-27 08:26

    It sounds like you have nothing set in your $pera variable. If you have to define a variable outside a function, try passing its value as argument to your function.

    function echoMyVar( $myVar )
    {
       echo $myVar;
    }
    
    
    $p = "toto";
    echoMyVar($p);
    
    0 讨论(0)
  • 2020-11-27 08:40

    In your function function provera($prom) add a line that says

    global $pera;

    0 讨论(0)
  • 2020-11-27 08:43

    This is because you're using the $pera variable (which exists only in the global scope) inside a function.

    See the PHP manual page on variable scope for more information.

    You could fix this by adding global $pera; within your function, although this isn't a particularly elegant approach, as global variables are shunned for reasons too detailed to go into here. As such, it would be better to accept $pera as an argument to your function as follows:

    function provera($prom, $pera){
        if (preg_match("/[0-9\,\.\?\>\.<\"\'\:\;\[\]\}\{\/\!\\\@\#\$\%\^\&\*\(\)\-\_\=\+\`[:space:]]/",$prom)){
            echo "Nepravilan unos imena ili prezimina!";
            echo $pera;
            }
    }
    
    0 讨论(0)
  • 2020-11-27 08:43

    If your PHP version is on 5.3 or later versions, closure can be applied.

    Closures may also inherit variables from the parent scope.

    use is the php syntax to implement closure.

    ref: Anonymous functions

        <?php
        // $ime=$_POST["ime"];
        // $prezime=$_POST["prezime"];
        $pera="string";
        $prezime = "Ne radi, vrati se nazad i unesi nesto!";
        // if (empty($ime)||empty($prezime)){
        //     echo "Ne radi, vrati se nazad i unesi nesto!";
        // }
        $provera = function ($prom) use ($pera) {
            if (preg_match("/[0-9\,\.\?\>\.<\"\'\:\;\[\]\}\{\/\!\\\@\#\$\%\^\&\*\(\)\-\_\=\+\`[:space:]]/",$prom)){
                echo "Nepravilan unos imena ili prezimina!";
                echo $pera;
            }
        };
    
        // $provera($ime);
        $provera($prezime);
    
    0 讨论(0)
提交回复
热议问题