现在,看看我的page.php
,我将解释它内部的问题。
<?php
$var= "<p>Hello world</p>";
function myfunction1($a){
echo $a;
}
//then
myfunction1($var);//-->OK, return "Hello world!"
//but, the thing is, i don't want to pass any argument into myfunction(),
//so i have to import the external $var into myfuntion2()
function myfunction2(nothing here){
//what's here?
}
myfunction2();//i want to do this
?>
当然,如果我把所有这些都封装在一个CLASS中,那么myfunction()
和$var
就变成了method $amp; property
(OOP风格),这些将是如此容易访问!但我不想那样做!
那么,有可能吗?有人能给我一个建议吗?感谢
如果您不想在函数中传递任何参数,唯一的方法就是使用global
function myfunction2(){
global $var;
}
但我应该警告您,使用global
是非常糟糕的,所以除非您知道它的行为,否则不要使用它。您的global $var
可以在您的功能中更改,例如
$var = 2; //Initial value
function myfunction2(){
global $var;
$var = 'changed';
}
myfunction2(); //$var is now holding 'changed'. 2 is now lost
因此,从现在起,$var
将保存字符串changed
,因为$var
具有global
作用域,它不再是函数的本地作用域。
或者,您可以阅读此答案以传递函数作为函数参数
您可以在现代版本的PHP:中执行此操作
$var = 'World';
$func = function() use($var){
echo "Hello $var";
};
$func(); //=> Hello World
或者使用Singleton:
function myfunction2(){
echo MySingleton::getInstance()->var2;
}
您必须在函数中将变量声明为全局变量,然后才能在函数内部使用变量,而无需将其作为parameter传递。
像这样,
<?php
$var= "<p>Hello world</p>";
function myfunction1($a){
echo $a;
}
//then
myfunction1($var);//-->OK, return "Hello world!"
//but, the thing is, i don't want to pass any argument into myfunction(), so i have to import the external $var into myfuntion2()
function myfunction2(){
global $var;
echo $var;
}
myfunction2();//i want to do this
?>