从PHP的外部获取变量 [英] Get variables from the outside, inside a function in PHP

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

问题描述

我试图弄清楚如何使用一个已经在函数外部设置的变量。有没有办法做到这一点?我试图将该变量设置为全局,但它似乎没有按预期工作。



我的代码的一个简单示例

  $ var ='1'; 

function(){
$ var + 1;
返回$ var;
}

我想要这个,要返回2的值。

解决方案

您需要在函数中使用全局关键字
http://php.net/manual/en/language.variables.scope.php

编辑(尴尬我忽视了这一点,感谢评论者)



...并将结果存储在某处

  $ var ='1'; 
function(){
global $ var;
$ var + = 1; //你确定你想同时改变$ var
的值$ return $ var; //并返回值?
}


I'm trying to figure out how i can use a variable, that has been set outside a function, inside. Is there any way of doing this? I've tried to set the variable to "global" but it doesn't seems to work out as expected.

A simple example of my code

$var = '1';

function() {
$var + 1;
return $var;
}

i want this, to return the value of 2.

解决方案

You'll need to use the global keyword inside your function. http://php.net/manual/en/language.variables.scope.php

EDIT (embarrassed I overlooked this, thanks to the commenters)

...and store the result somewhere

$var = '1';
function() {
    global $var;
    $var += 1;   //are you sure you want to both change the value of $var
    return $var; //and return the value?
}

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

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