问题描述
我是PHP新手,所以我有一个小问题功能。
我有这段代码:
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);
?>
无论如何,当我尝试使用此代码时,我总是收到一条错误消息,说明第11行有错误代码的大胆部分),并且没有变量被回显,我猜测它给了我那个错误,因为我的变量没有被定义在该函数内部,但是我需要在函数外部定义它,所以有没有办法要做到这一点?
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?
推荐答案
这是因为您使用 $ pera
变量(它只存在于全局s中) )
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.
你可以通过添加 global $ pera来解决这个问题。 ;
在你的函数中,尽管这不是一个特别优雅的方法,因为全局变量因为太详细的原因而被忽略掉了。因此,最好接受 $ pera
作为你函数的参数,如下所示:
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;
}
}
这篇关于PHP函数未定义的变量问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!