PHP 函数使用外部变量 [英] PHP function use variable from outside

查看:20
本文介绍了PHP 函数使用外部变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

function parts($part) { 
    $structure = 'http://' . $site_url . 'content/'; 
    echo($tructure . $part . '.php'); 
}

此函数使用在此页面顶部定义的变量 $site_url,但此变量未传递到函数中.

This function uses a variable $site_url that was defined at the top of this page, but this variable is not being passed into the function.

我们如何让它在函数中返回?

How do we get it to return in the function?

推荐答案

添加第二个参数

您需要将附加参数传递给您的函数:

You need to pass additional parameter to your function:

function parts($site_url, $part) { 
    $structure = 'http://' . $site_url . 'content/'; 
    echo $structure . $part . '.php'; 
}

在关闭的情况下

如果您更愿意使用闭包,那么您可以将变量导入当前范围(use 关键字):

If you'd rather use closures then you can import variable to the current scope (the use keyword):

$parts = function($part) use ($site_url) { 
    $structure = 'http://' . $site_url . 'content/'; 
    echo $structure . $part . '.php'; 
};

global - 不好的做法

global - a bad practice

这篇文章经常被阅读,所以需要澄清一些关于global的内容.使用它被认为是一种不好的做法(请参阅 thisthis).

This post is frequently read, so something needs to be clarified about global. Using it is considered a bad practice (refer to this and this).

为了完整起见,这里是使用 global 的解决方案:

For the completeness sake here is the solution using global:

function parts($part) { 
    global $site_url;
    $structure = 'http://' . $site_url . 'content/'; 
    echo($structure . $part . '.php'); 
}

它有效是因为你必须告诉解释器你想使用一个全局变量,现在它认为它是一个局部变量(在你的函数中).

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).

推荐阅读:

这篇关于PHP 函数使用外部变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆