php bind variable to function's scope in older

2019-07-21 03:36发布

问题:

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.



标签: php scope bind