4

我已经阅读了有关使用与仅调用函数的堆栈call_user_func_array上的其他答案,但我仍然无法收集何时应该使用前者。call_user_func_array我知道当您不知道传递了多少个参数时您可能想要使用,因此您可以这样做: $args = func_get_args();...但是如果要在函数中使用参数,您是否总是需要知道参数?

以下两项工作,我假设第一项的开销较小。

$format = new Foo;
$method = 'somemethod';
$arg = 'somevalue';
if (method_exists($format, $method)) {
    return $format->$method($arg);
}

对比

return call_user_func_array(array($format, $method), array($arg));

什么时候才能真正受益于使用call_user_func_array

4

4 回答 4

3

call_user_func_array 非常有用的一个例子

假设您希望访问一个对象,但是通过静态方法,如下所示:

Helper::load();

好吧,这本身是行不通的,因为如果您查看具体类,它没有静态方法:

class Helper {

  public function load()
  {
      // Do some loading ...
  }

  public function aFunctionThatNeedsParameters( $param1, $param2 )
  {
      // Do something, and $param1 and $param2 are required ...
  }
}

所以在第二个类中,我们可以这样做,因为上面的 Helper 类被加载到依赖注入容器中(请注意,这两个 Helper 类的名称相同,但在不同的命名空间中):

class Helper extends DIContainer {

  public static $helper_instance = NULL;

  public static function get_instance()
  {
    if( is_null( self::$helper_instance ) )
    {
      self::$helper_instance = parent::$container['helper'];
    }

    return self::$helper_instance;
  }

  public static function __callStatic( $method, $params )
  {
    $obj = self::get_instance();

    return call_user_func_array( [ $obj, $method ], $params );
  }
}

问题是,可能还有另一种方法需要参数,即使我们的加载方法没有任何参数。

所以在这种情况下我们可以使用Helper::load(), 而且Helper::aFunctionThatNeedsParameters( $param1, $param2 )

我认为这在知道静态类通常不合适的 PHP 框架中被大量使用,但他们希望能够像调用静态方法一样调用方法。我希望这是有道理的。

于 2017-12-24T20:36:26.977 回答
2

David Sklar在他的PHP Cookbook中解决了何时使用call_user_func_array的问题。因此,要关注 OP 的一条评论:

“......如果要在函数中使用参数,您是否总是需要知道参数?”

这是 call_user_func() 可以派上用场的一个实例:

<?php

function Test(){
  $args = func_get_args();
  call_user_func_array("printf",$args);
}

Test("Candidates 2014: %s %s %s %s\n","Tom","Debbie","Harry", "Sally");
Test("Candidates 2015: %s %s\n","Bob","Sam","Sarah");

查看实时代码

使用 call_user_func_array() 和 func_get_args() 对,用户定义函数 Test() 可以采用可变数量的参数。

此外,对于聚合方法很有用(请参阅 PHP Cookbook p208-210),如以下简化示例所示:

<?php
class Address {
   protected $city;

   public function getCity() {
      return $this->city;
   }
   public function setCity($city) {
      $this->city=$city;
   }
}

class Person {
     protected $name="Tester";
     protected $address;

     public function __construct() {
            $this->address = new Address;
     }
     public function getName(){
            return $this->name;
     }
    public function __call($method, $args){
           if (method_exists($this->address,$method)) {
                return call_user_func_array( array($this->address,$method),$args);
           }
    }
}

  $sharbear = new Person;
  echo $sharbear->setCity("Baltimore");
  echo "Name: ",$sharbear->getName(),"\n";
  echo "City: ",$sharbear->getCity();

查看实时代码

附录

自 PHP 5.6 起,PHP 支持可变参数函数参数解包,因此 call_user_func() 和 func_get_args() 可以针对可变参数进行替换,如下所示:

<?php

function Test(...$args){

   printf(...$args);
}
$namesT = ["Timmy","Teddy","Theo","Tad"];
$namesB = ["Bobby","Bill","Brad"];

Test("T Names: %s %s %s %s\n",...$namesT);
Test("B Names: %s %s %s\n",...$namesB);

查看实时代码

于 2017-12-24T21:03:10.247 回答
2

<!-- begin snippet: js hide: false console: true babel: false -->

<pre>
I use call_user_func_array when I need to call a function or php function from my ajax enabled page. 

eg.
in html and javascript:

<form id='my-form'>

<input id='name' value='Wong, Billy'>
<input id='age' value='50'>

<a href='javascript;' onClick="xjx.query('helloWorld', $('#name').val(), $('#age').val())">Show name and age</a>

<a href='javascript;' onClick="xjx.query('showName', $('#name').val())">Show name</a>

<a href='javascript;' onClick="xjx.query('showAge', $('#age').val())">Show age</a>

<a href='javascript;' onClick="xjx.post('#my-form', 'showPost', 'live long and prosper')">Show age</a>

</form>

xjx.query and xjx.post, personal javascript functions of mine will then format and submit to the php page via ajax

in php
$method = $_POST['method'];
$args = $_POST['args'];

call_user_func_array($method, $args)

function helloWorld($name, $age) {
    ....
}

function showName($name) {
    ....
}

function showAge($age) {
    ....
}

function showPost($f, $message) {
   print_r($f);
   echo $message;
}

my libs are found in github with xjx as the project name
</pre>
于 2020-06-30T03:59:55.810 回答
0

假设我们有几节课

class Request 
{
    private $req;

    public function __construct($req)
    {
        $this->req = $req;
    }

    public function __call($name, $arg)
    {
        return \call_user_func_array(array($this->req,$name), $arg);
    }
}

class Get 
{
    public function load($url)
    {
        // fire an http request
    }
}

class Post 
{
    public function load($url)
    {
        // fire an http request
    }

    public function attachHeader($header=[])
    {
        // attach an header to the request
    }
}

$request_1 = new Request(new Get());
$request_1->load($url);

$request_2 = new Request(new Post());
$request_2->attachHeader($header_data);
$request_2->load($url);

在这里您可以看到我们可以 毫无问题地attachHeader()使用 of 调用该方法。call_user_func_array()

我希望它会有所帮助

于 2020-07-30T06:06:05.497 回答