![](/img/trans.png)
[英]I can see the array outside function, but no inside the function, how pass variable inside function?
[英]how can i make a function see a variable outside it
如何在运行函数时将变量放在函数内,以便preg_match正确的信息。 这是我现有的代码:
$username = "test";
function is_txt($file) {
return preg_match('/backup-[0-9]+\.[0-9]+\.[0-9]+_[0-9]{2}-[0-9]{2}-[0-9]{2}_'.$username.'.tar.gz/', $file) > 0;
}
我试图做的是从函数外部拉出$ username变量并允许它在其中被看到所以我可以在我的while循环中拉出正确的匹配。 虽然前面的内容空白,但是如果我执行以下操作它会起作用:
$username = "test";
function is_txt($file) {
$username = "test";
return preg_match('/backup-[0-9]+\.[0-9]+\.[0-9]+_[0-9]{2}-[0-9]{2}-[0-9]{2}_'.$username.'.tar.gz/', $file) > 0;
}
修改函数以将$username
变量作为参数:
function is_txt($file, $u) {
return preg_match('/backup-[0-9]+\.[0-9]+\.[0-9]+_[0-9]{2}-[0-9]{2}-[0-9]{2}_'.$u.'.tar.gz/', $file) > 0;
}
然后称之为:
$username = "test";
is_txt($file, $username);
或者,您可以使用global
关键字使函数可见变量。 这有时很有用,但不应该在所有地方使用。 有关详细信息,请参阅变量范围手册条目。
您需要使用global
导入var:
function is_txt($file) {
global $username;
return preg_match('/backup-[0-9]+\.[0-9]+\.[0-9]+_[0-9]{2}-[0-9]{2}-[0-9] {2}_'.$username.'.tar.gz/', $file) > 0;
}
但是,在大多数情况下,将值作为Jonah解释的参数传递是更好的解决方案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.