PHP:变量在函数内部不起作用? [英] PHP: variable not working inside of function?
本文介绍了PHP:变量在函数内部不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
echo $path; //working
function createList($retval) {
echo $path; //not working
print "<form method='POST' action='' enctype='multipart/form-data'>";
foreach ($retval as $value) {
print "<input type='checkbox' name='deletefiles[]' id='$value' value='$value'>$value<br>";
}
print "<input class='submit' name='deleteBtn' type='submit' value='Datei(en) löschen'>";
print "</form>";
}
我做错了什么?为什么 $path 在 createList
函数外正确打印,但在函数内无法访问?
what am I doing wrong? why is $path printed correctly outside of the createList
function, but it's not accessible inside the function?
推荐答案
因为没有在函数中定义.
有几种方法可以解决这个问题:
Because it's not defined in the function.
There are a few ways to go about this:
1) 使用 Alex 所说的,告诉函数它是一个全局变量:
echo $path; // working
function createList($retval) {
global $path;
echo $path; // working
}
2) 将其定义为常量:
define(PATH, "/my/test/path"); // You can put this in an include file as well.
echo PATH; // working
function createList($retval) {
echo PATH; // working
}
3) 如果它特定于该函数,则将其传递给函数:
echo $path; // working
function createList($retval, $path) {
echo $path; // working
}
根据该功能的实际工作方式,其中之一可以.
Based on how the function really works, one of those will do ya.
这篇关于PHP:变量在函数内部不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文