Recommended replacement for deprecated call_user_m

2020-02-05 05:54发布

Since PHP's call_user_method() and call_user_method_array() are marked deprecated I'm wondering what alternative is recommended?

One way would be to use call_user_func(), because by giving an array with an object and a method name as the first argument does the same like the deprecated functions. Since this function is not marked deprecated I assume the reason isn't the non-OOP-stylish usage of them?

The other way I can think of is using the Reflection API, which might be the most comfortable and future-oriented alternative. Nevertheless it's more code and I could image that it's slower than using the functions mentioned above.

What I'm interested in:

  • Is there a completely new technique for calling an object's methods by name?
  • Which is the fastest/best/official replacement?
  • What's the reason for deprecation?

4条回答
爷的心禁止访问
2楼-- · 2020-02-05 06:32

As you said call_user_func can easily duplicate the behavior of this function. What's the problem?

The call_user_method page even lists it as the alternative:

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

As far as to why this was deprecated, this posting explains it:

This is because the call_user_method() and call_user_method_array() functions can easily be duplicated by:

old way:
call_user_method($func, $obj, "method", "args", "go", "here");

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

Personally, I'd probably go with the variable variables suggestion posted by Chad.

查看更多
爷、活的狠高调
3楼-- · 2020-02-05 06:34

You could do it using variable variables, this looks the cleanest to me. Instead of:

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

You do:

$obj->{$method_name}($parameter);
查看更多
看我几分像从前
4楼-- · 2020-02-05 06:43

if you get following error: Warning: call_user_func() expects parameter 1 to be a valid callback, second array member is not a valid method in C:\www\file.php on line X and code like this:

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

use (string) declaration for $method name

call_user_func(array($this, (string)$method));
查看更多
▲ chillily
5楼-- · 2020-02-05 06:50

Do something like that :

I use something like that in my __construct() method.

$params = array('a','b','c'); // PUT YOUR PARAMS IN $params DYNAMICALLY

call_user_func_array(array($this, $this->_request), array($params));

1st argument : Obect instance, 2nd argument : method to call, 3rd argument : params

Before you can test if method or Class too, with :

method_exists()
class_exists()

Cheers

查看更多
登录 后发表回答