【问题标题】:php bind variable to function's scope in older PHPphp 将变量绑定到旧 PHP 中的函数范围
【发布时间】:2011-04-03 22:09:50
【问题描述】:

我想将变量绑定到函数的作用域,我可以在 PHP 5.3 之后使用 'use' 关键字在 php 中执行此操作,但是如何在版本 test_use_keyword(); 功能 test_use_keyword(){ $测试=2; $res=array_map( 函数($el)使用($test){ 返回 $el * $test; }, 数组(3) ); print_r($res); }

【问题讨论】:

  • PHP

标签: php scope bind


【解决方案1】:

您可以使用全局变量,但应始终尽可能避免使用全局变量。作为一个建议,不知道你想用这个解决什么

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

旧的 lambdas 也有可能

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

【讨论】:

    【解决方案2】:

    通常通过全局变量,认真的。尽管可以使用黑客来模仿功能,例如partial functions in php。摘自文章:

    function partial()
    {
      if(!class_exists('partial'))
      {
        class partial{
            var $values = array();
            var $func;
    
            function partial($func, $args)
            {
                $this->values = $args;
                $this->func = $func;
            }
    
            function method()
            {
                $args = func_get_args();
                return call_user_func_array($this->func, array_merge($args, $this->values));
            }
        }
      }
      //assume $0 is funcname, $1-$x is partial values
      $args = func_get_args();   
      $func = $args[0];
      $p = new partial($func, array_slice($args,1));
      return array($p, 'method');
    }
    

    只有在那之后你才能拥有类似的东西。

    function multiply_by($base, $value) {
      return $base * $value;
    }
    
    // ...
    $res = array_map(partial("multiply_by", $test), array(3));
    

    不......值得......它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-09-14
      • 1970-01-01
      • 2016-10-26
      • 1970-01-01
      • 2013-10-28
      • 2014-11-10
      • 1970-01-01
      相关资源
      最近更新 更多