PHP:变量不在函数内部工作? [英] PHP: variable not working inside of function?
本文介绍了PHP:变量不在函数内部工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
echo $ path; //工作
函数createList($ retval){
echo $ path; //不工作
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'>;
打印< / form>;
}
我做错了什么?为什么在$ createList
函数之外正确打印$ path,但它在函数内部不可访问?
解决方法
因为它没有在函数中定义。
有几种方法可以解决这个问题:
1)使用Alex通过告诉函数它是一个全局变量来表示:
echo $ path; //工作
函数createList($ retval){
global $ path;
echo $ path; //正在工作
2)将其定义为常量:
define(PATH,/ my / test / path); //你也可以把它放在一个包含文件中。
echo PATH; //工作
函数createList($ retval){
echo PATH; //工作
3)将函数传递给该函数:
echo $ path; //工作
函数createList($ retval,$ path){
echo $ path; //正在工作
根据函数的实际工作方式,其中一个将会执行。
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>";
}
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) Use what Alex said by telling the function it is a global variable:
echo $path; // working
function createList($retval) {
global $path;
echo $path; // working
2) Define it as a constant:
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) Pass it into the function if it's specific to that function:
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屋!
查看全文