代码之家  ›  专栏  ›  技术社区  ›  okoman

建议替换不推荐的call\u user\u方法?

  •  23
  • okoman  · 技术社区  · 17 年前

    自从PHP的 call_user_method() 和 call_user_method_array() 是否标记为已弃用?我想知道推荐的替代方案是什么?

    call_user_func() ,因为通过将对象和方法名作为第一个参数提供给数组,与不推荐使用的函数一样。既然这个函数没有被标记为不推荐,我想原因不是它们的非OOP风格用法?

    我能想到的另一种方法是使用 Reflection API ,这可能是最舒适和面向未来的选择。尽管如此,它的代码更多,我可以想象它比使用上面提到的函数要慢。

    • 有没有一种全新的方法可以通过名称调用对象的方法?
    • 哪一个是最快/最好/正式的替代品?
    • 反对的理由是什么?
    4 回复  |  直到 14 年前
        1
  •  28
  •   Paolo Bergantino    17 年前

    正如你所说 call_user_func 可以轻松复制此函数的行为。有什么问题吗?

    这个 call_user_method 页面甚至将其列为备选方案:

    <?php
    call_user_func(array($obj, $method_name), $parameter /* , ... */);
    call_user_func(array(&$obj, $method_name), $parameter /* , ... */); // PHP 4
    ?>
    

    至于 这是不赞成的, this posting explains it:

    这是 因为 call_user_method() 和 call_user_method_array()

    老办法:
    call_user_method($func, $obj, "method", "args", "go", "here");


    call_user_func(array(&$obj, "method"), "method", "args", "go", "here");

    就我个人而言,我可能会赞同查德提出的变量建议。

        2
  •  18
  •   Chad Birch    17 年前

    你可以使用 variable variables

    call_user_func(array($obj, $method_name), $parameter);
    

    你可以:

    $obj->{$method_name}($parameter);
    
        3
  •  1
  •   Daminux    13 年前

    这样做:

    $params = array('a','b','c'); // PUT YOUR PARAMS IN $params DYNAMICALLY
    
    call_user_func_array(array($this, $this->_request), array($params));
    

    第一个参数:对象实例, 第二个参数:要调用的方法,

    在测试方法或类是否也存在之前,请执行以下操作:

    method_exists()
    class_exists()
    

    干杯

        4
  •  0
  •   HausO    13 年前

    如果出现以下错误: 代码如下:

    call_user_func(array($this, $method));
    

    call_user_func(array($this, (string)$method));
    
    推荐文章