封闭内的php变量引用

时间:2016-10-24 21:08:14

标签: php

我无法在闭包周围传递引用:

class stdobject {
    public function __call($method, $arguments) {    
        if (isset($this->{$method}) && is_callable($this->{$method})) {
            return call_user_func_array($this->{$method}, $arguments);
        } else {
            throw new Exception("Fatal error: Call to undefined method: $method");
        }
    }
}

$mod=function(){
  $test=new stdobject();

  $mode;

  $test->init=function($params) use (&$mode) {
    $mode =& $params['opmode'];
  };

  $test->setup=function() use (&$mode) {
    $mode='test';
  };

  return $test;
};

$opmode='helloworld';

$test=$mod();
$test->init([ 'opmode' => &$opmode ]);

$test->setup();

echo $opmode;  //should display test

我希望setup函数能够在外部范围内修改$opmode,这可能不是全局范围,任何人都能指出我如何实现这个目标的正确方向吗?

1 个答案:

答案 0 :(得分:1)

我不确定你为什么会这样,但我想这就是你想要实现的目标:

class stdobject {
    public function __call($method, $arguments) {    
        if (isset($this->{$method}) && is_callable($this->{$method})) {
            return call_user_func_array($this->{$method}, $arguments);
        } else {
            throw new Exception("Fatal error: Call to undefined method: $method");
        }
    }
}

$mod = function() {
    $self = new stdobject();

    $self->init = function ($params) use ($self) {
        $self->_opmode = &$params['opmode'];
    };

    $self->setup = function () use ($self) {
       $self->_opmode = 'dog';
    };

    $self->print = function () use ($self) {
        echo $self->_opmode . "\n";
    };

    return $self;
};

$obj = $mod();

$reference = 'fish';

$obj->init(['opmode' => &$reference]);
$obj->print();  // fish

$obj->setup();
$obj->print();  // dog

$reference = 'cats';
$obj->print();  // cats

https://3v4l.org/SLAri

但是我更喜欢这个:

<?php
class Mod {
    private $opmode;

    public function init($params)
    {
        $this->opmode = &$params['opmode'];
    }

    public function setup()
    {
        $this->opmode = 'dog';
    }

    public function print()
    {
        echo $this->opmode . "\n";
    }

}

$obj = new Mod();

$reference = 'fish';
$obj->init(['opmode' => &$reference]);
$obj->print();  // fish

$obj->setup();
$obj->print();  // dog

$reference = 'cats';
$obj->print();  // cats

https://3v4l.org/T9qr2