【发布时间】:2015-01-03 22:48:13
【问题描述】:
所以,我有这样的事情:
class ClassA{
public function doCallback($callback){
call_user_func_array($callback, array());
}
public function doSomething(){
return 12345;
}
}
class ClassB{
public function runMe(){
$classA = new ClassA();
$classA->doCallback(function(){
$this->doSomething();
});
}
}
我试图弄清楚,如果可能的话,我如何在回调函数中使用$this 或类似的东西,如果这有意义的话,它将引用正在运行回调的类(不是它所在的类) .
所以在我上面的例子中,我想要$this->doSomething();,其中$this 表示ClassA 而不是ClassB。目前$this 指的是ClassB。有什么我可以说我想要ClassA吗?
编辑
这是我使用的实际方法
public function save(){
$id = (int)$this->input->post("id");
$title = $this->input->post("title");
$uid = (int)$this->session->get("id");
$this->db->getTable("content")
->has(array("user_id" => $uid, "name" => $title), function(){
echo json_encode(array("error" => "Name already exists."));
}, function() use($id, $uid, $title){
//$this->db->getTable("content")
$this->update(array("name" => $title), array(
"user_id" => $uid,
"content_id" => $id), function($rows){
if($rows > 0){
$error = "";
}else{
$error = "Unknown error occurred";
}
echo json_encode(array("error" => $error));
});
});
}
$this->db->getTable("content") 返回一个数据库对象,has() 是对象中的一个方法。我希望我可以使用速记方式访问$this->db->getTable("content"),而不必在回调中再次调用它,或者将它作为参数传递给call_user_func_array,或者不使用use()。
方法has():
https://github.com/ZingPHP/Zing/blob/master/Zing/src/Modules/Database/DBOTable.php#L311
编辑
我认为在我的回调函数中我需要做这样的事情,但我认为它不起作用:
public function myFunc(callback $callback){
$callback->bindTo($this, $this);
return call_user_func_array($callback, array());
}
【问题讨论】:
-
你不能只做
$classA->doCallback(function() use ($classA){ $classA->doSomething(); });? -
在上面的例子中是的,但在我的实际代码中,代码不会以这种方式初始化数据
-
使用
call_user_func_array($callback, array($this));然后$classA->doCallback(function($c) { $c->doSomething(); });传递ClassA 的实例怎么样? -
我考虑这样做是最后的手段。
-
为什么?你能改进你的问题的细节吗?你能举一个更具体的例子来说明你想要实现的目标吗?