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

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

问题描述

我想弄清楚如何使用在函数外部、函数内部设置的变量.有没有办法做到这一点?我试图将变量设置为全局",但似乎没有按预期工作.

I'm trying to figure out how I can use a variable that has been set outside a function, inside a function. 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;
}

我希望它返回 2 的值.

I want this to return the value of 2.

推荐答案

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

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

EDIT(不好意思我忽略了这一点,感谢评论者)

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天全站免登陆