php bind variable to function's scope in older PHP

家住魔仙堡 提交于 2019-12-11 01:56:00

问题


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

回答1:


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

Also possible are the good old lambdas

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



回答2:


Normally through globals, seriously. Although hacks could be used to mimic the functionality, like partial functions in php. Extracted from article:

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

And only after that could you have something like.

function multiply_by($base, $value) {
  return $base * $value;
}

// ...
$res = array_map(partial("multiply_by", $test), array(3));

Not... worth... it.



来源:https://stackoverflow.com/questions/5532887/php-bind-variable-to-functions-scope-in-older-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!