$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 Fatal error: Using $this when not in object context in /home/content/95/10799595/html/bin/test/anonymous_4.php on line 41 --> if(!$options) $options = $this->options;
我應該得到這個在我的本地主機是在php5.4,
init array (size=1) 0 => string 'hello world!' (length=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);
}
仍然得到一個錯誤。
Fatal error: Cannot access private property myclass::$options in /home/content/95/10799595/html/bin/test/anonymous_4.php on line 43
謝謝。我嘗試過,但仍然出現錯誤。請參閱我上面的編輯。謝謝。 – laukok
你需要告訴哪一行是43。 FWIW,我真的不明白你想要取得什麼成就,這似乎太複雜了。可能明智的看看,簡單的匿名函數,而不是那種東西會更好地工作:) – Smar
只需製作一個公共getOptions方法。你不能通過'$ self'直接訪問任何私人內容。 – danronmoon