我可以在PHP中的不同函数之间共享变量吗? [英] Can I share variables between different functions in PHP?

查看:135
本文介绍了我可以在PHP中的不同函数之间共享变量吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试着用一个例子来解释... ...

假设我有两个不同的函数,其中一个函数具有一个已定义的变量。在第二个函数中,我不想再次写同一个变量,我可以简单地使用第二个函数中的第一个函数的变量,而不是在第二个函数中重新定义它?

 函数a()
{
$ var =我的变量 ;
}

函数b()
{
echo $ var;
}

对不起,如果这个问题有点傻,但我仍然是初学者=)。

解决方案

当然你可以做全局变量,但PHP 5.3.0+有 匿名函数 ,所以你也可以做闭包:

 <?php 

函数a(){
$ a = 1;
echoFirst:$ a,;
++ $ a;

//这是一个闭包。它可以通过
// use选项访问a()的变量。
$ b = function()use($ a){
echosecond:$ a;
};
$ b();
};
a(); //输出:第一:1,第二:2
?>







或者可能更有用: =noreferrer>在此键盘示例中试用

 <?php 

函数a(){
$ a = 1;
echoFirst:$ a,;
++ $ a;
$ b = function()use($ a){
echosecond:$ a;
};
返回$ b;
};
$ fun = a(); // $ fun现在是$ b& $ b有权使用$ a!
$ fun();
//输出:第一:1,第二:2
?>





来自文档:


闭包也可以继承父范围的变量。任何这样的变量都必须在函数头部声明。从父范围继承变量与使用全局变量不同。全局变量存在于全局范围内,无论执行什么功能都是一样的。闭包的父范围是闭包被声明的函数(不一定是它被调用的函数)。



I'll try to explain with an example...

Let's say I have two different functions, and one of them has a defined variable. In the second function, I don't wanna write the same variable again, can I simply use the variable from the first function in the second one WITHOUT redefining it in the second function?

Something like:

function a()
{
  $var = "my variable";
}

function b()
{
 echo $var;
}

Sorry if this questions is a bit silly, but I'm still a beginner =).

解决方案

Sure you can do globals, but of PHP 5.3.0+ has anonymous functions, so you can also do closures:

<?php

function a(){
  $a = 1;  
  echo "First: $a, ";
  ++$a;

    // This is a closure. It can gain access to the variables of a() with the 
    // use option.
  $b = function() use ($a) {
      echo "second: $a";  
  };  
  $b();
};
a(); // Outputs: First: 1, second: 2
?>

Try it out at this Codepad example


or probably more useful:

<?php

function a(){
  $a = 1;  
  echo "First: $a, ";
  ++$a;
  $b = function() use ($a) {
      echo "second: $a";  
  };        
  return $b;
};
$fun = a();     // $fun is now $b & $b has access to $a!
$fun();
// Outputs: First: 1, second: 2
?>

Try it out at this Codepad example

From the docs:

Closures may also inherit variables from the parent scope. Any such variables must be declared in the function header. Inheriting variables from the parent scope is not the same as using global variables. Global variables exist in the global scope, which is the same no matter what function is executing. The parent scope of a closure is the function in which the closure was declared (not necessarily the function it was called from).

这篇关于我可以在PHP中的不同函数之间共享变量吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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