PHP函数使用来自外部的变量 [英] PHP function use variable from outside
问题描述
函数部分($ part){
$ structure ='http://'。 $ site_url。 '内容/';
echo($ tructure。$ part。'.php');
$ / code>
这个函数使用一个变量 $ site_url
,它是在页面顶部定义的,但是这个变量没有被传入函数。
我们如何让它在函数中返回?
添加第二个参数
您需要将其他参数传递给您的函数:
函数部分($ site_url,$ part){
$ structure ='http://'。 $ site_url。 '内容/';
echo $结构。 $部分。 .PHP;
}
如果关闭
如果您想使用闭包,那么您可以将变量导入当前范围(使用
关键字):
$ parts = function($ part)use($ site_url){
$ structure ='http://'。 $ site_url。 '内容/';
echo $结构。 $部分。 .PHP;
全球
- 一个不好的做法
这篇文章经常被阅读,所以需要澄清 为了完整起见,这里是使用 它的作用是因为你必须告诉解释器你想使用全局变量,现在它认为它是一个局部变量(在你的函数中)。 建议阅读: This function uses a variable How do we get it to return in the function? Add second parameter You need to pass additional parameter to your function: In case of closures If you'd rather use closures then you can import variable to the current scope (the This post is frequently read, so something needs to be clarified about For the completeness sake here is the solution using It works because you have to tell interpreter that you want to use a global variable, now it thinks it's a local variable (within your function). Suggested reading: 这篇关于PHP函数使用来自外部的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋! global
。使用它被认为是不好的做法(参考这和这
global
的解决方案:
函数部分($ part){
global $ site_url;
$ structure ='http://'。 $ site_url。 '内容/';
echo($ structure。$ part。'.php');
}
function parts($part) {
$structure = 'http://' . $site_url . 'content/';
echo($tructure . $part . '.php');
}
$site_url
that was defined at the top of this page, but this variable is not being passed into the function. function parts($site_url, $part) {
$structure = 'http://' . $site_url . 'content/';
echo $structure . $part . '.php';
}
use
keyword):$parts = function($part) use ($site_url) {
$structure = 'http://' . $site_url . 'content/';
echo $structure . $part . '.php';
}
global
- a bad practiceglobal
. Using it is considered a bad practice (refer to this and this).global
:function parts($part) {
global $site_url;
$structure = 'http://' . $site_url . 'content/';
echo($structure . $part . '.php');
}