Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
242 views
in Technique[技术] by (71.8m points)

Undefined variable problem with PHP function

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

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

Anyway, when I try this code I always get an error message saying that there's a error on on line 11 (the bold part of the code) and no variable is echoed. I'm guessing that it gives me that error because my variable isn't defined inside of that function, but I need to define it outside of the function so is there a way to do this?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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;
        }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...