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

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

问题描述

 函数部分($ 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;

全球 - 一个不好的做法

这篇文章经常被阅读,所以需要澄清 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'); 
}

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?

解决方案

Add second parameter

You need to pass additional parameter to your function:

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

In case of closures

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 - a bad practice

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

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

Suggested reading:

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

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