php将变量绑定到旧版PHP中函数的作用域 [英] php bind variable to function's scope in older PHP

查看:73
本文介绍了php将变量绑定到旧版PHP中函数的作用域的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将变量绑定到函数的作用域,我可以在PHP 5.3之后在php中使用'use'关键字进行此操作,但是在版本<中,我该怎么做? PHP 5.3?

I would like to bind a variable to a function's scope, I can do this in php use the 'use' keyword after PHP 5.3, however how do I do the equivalent in versions < PHP 5.3?


  test_use_keyword();
  function test_use_keyword(){
    $test =2;
    $res=array_map(
      function($el) use ($test){
        return $el * $test;
      }, 
      array(3)
    );
    print_r($res); 
  }

推荐答案

您可以使用全局变量,但应尽可能避免使用全局变量.作为建议,您不知道自己要解决的问题

You can use a global variable, but you should always avoid globals variables whereever possible. As a suggestion, without knowing, what you are trying to solve with this

class Xy ( {
  private $test;
  public function __construct ($test) {
    $this->test = $test;
  }
  public function call ($el) {
    return $el * $this->test;
  }
}

print_r(array_map(array(new Xy(2), 'call'), array(3));

好的老lambda也可能

Also possible are the good old lambdas

$test = 2;
$a = create_function ('$el', 'return $el * ' . $test . ';');
print_r (array_map($a, array(3)));

这篇关于php将变量绑定到旧版PHP中函数的作用域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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