$this
php5.3.x 类中的匿名函数不支持,我该如何解决这个问题,以便将$this
信息/数据传递给匿名函数?我怎样才能写一个回退到 php5.3.x?
class anonymous {
protected $methods = array();
public function __construct(array $options)
{
$this->methods = $options;
}
public function __call($name, $arguments)
{
$callable = null;
if (array_key_exists($name, $this->methods))
$callable = $this->methods[$name];
elseif(isset($this->$name))
$callable = $this->$name;
if (!is_callable($callable))
throw new BadMethodCallException("Method {$name} does not exists");
return call_user_func_array($callable, $arguments);
}
}
class myclass {
private $options = array();
public function __construct($options = array()){
$this->options = $options;
}
public function hello($data = null, $options = array()){
$methods = new anonymous(array(
"init" => function($options) {
echo "init";
if(!$options) $options = $this->options;
return $options;
},
"run" => function($options) {
echo "run";
return $options;
}
));
$default = array(
"method" => "init",
"options" => array()
);
if($data === null) {
$method = "init";
} else if (is_string($data)) {
$method = $data;
} else if(is_array($data)) {
$method = "init";
$options = $data;
}
// Return the requested method.
return $methods->$method($options);
}
}
因此对于,
$myclass = new myclass(array("hello world!"));
var_dump($myclass->hello());
结果,
init 致命错误:在第 41 行的 /home/content/95/10799595/html/bin/test/anonymous_4.php 的对象上下文中使用 $this --> if(!$options) $options = $this->选项;
我应该在 php5.4 上的本地主机中得到这个,
初始化数组 (size=1) 0 => 字符串 'hello world!' (长度=12)
有什么解决办法和建议吗?
编辑:
public function hello($data = null, $options = array()){
$self = $this;
$methods = new anonymous(array(
"init" => function($options) use($self){
echo "init";
if(!$options) $options = $self->options;
return $options;
},
"run" => function($options) {
echo "run";
return $options;
}
));
$default = array(
"method" => "init",
"options" => array()
);
if($data === null) {
$method = "init";
} else if (is_string($data)) {
$method = $data;
} else if(is_array($data)) {
$method = "init";
$options = $data;
}
// Return the requested method.
return $methods->$method($options);
}
仍然得到一个错误。
致命错误:无法访问第 43 行 /home/content/95/10799595/html/bin/test/anonymous_4.php 中的私有属性 myclass::$options