使用PHP从回调参数调用类方法

4

我想从A类中实现一个回调,它包括特定的方法作为参数。例如:

    call_user_func_array($callback, ['$this->get', '$this->post']);

然而这并不起作用。我在这里的目标是做到这一点:
index.php
    $API = new API();
    $API->state('/users', function ($get, $post) {
        $get('/', 'UserController.getAll');
    });

API.php

    public function state ($state, $callback) {
        call_user_func_array($callback, ['$this->get', '$this->post']);
    }

    public method get ($uri, $ctrl)  { echo 'getting'; }
    public method post ($uri, $ctrl) { echo 'posting'; }

感谢您的任何输入!我知道使用 $this->method 是行不通的,因为在回调范围内,$this-> 不存在。


我的PHP版本是5.5.12。 - andersfylling
3个回答

1
我发现必须将 $this 绑定到正确的作用域。我通过在每个参数中包含 $this(类实例)来成功实现了这一点。
call_user_func_array($callback, [ [$this, 'get'] ]);

0
如果您只需要访问公共成员和方法,则可能的解决方案之一是这样的:
class API{
  public function state ($state, $callback) {
      call_user_func($callback, $this);
  }

  public function get ($uri, $ctrl)  { echo 'getting'; }
  public function post ($uri, $ctrl) { echo 'posting'; }
}

$API = new API();
$API->state('/users', function ($context) {
    $context->get('/', 'UserController.getAll');
});

如果我想要这样做,更容易的方法是将$API添加到函数作用域中,而不是从类作用域本身包含this变量。 - andersfylling

0

因为您正在使用对象方法而不是全局函数作为回调,所以必须使用call_user_method_array而不是call_user_func_array


这将会给我一个注释:只有变量可以作为参数传递回来。在阅读相关资料后,我发现这已经被弃用,并且在PHP 7中已经完全移除。 - andersfylling
call_user_method_array自PHP 4.1.0版本起已被弃用,并在PHP 7中删除。 - Tekay37
根据我在PHP文档中的了解,call_user_method_array已经被弃用;现在应该使用call_user_func_array(array($this, $callback), $params); - ul90
你应该再次阅读文档,第一个参数应该是可调用的变量,而不是数组。 - andersfylling
现在我感觉很愚蠢,我本应该说的是:“我遇到了一个错误:() 期望参数 1 是有效的回调函数,第二个数组成员不是有效的方法。” - andersfylling

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接