【问题标题】:PHP - Call class like call_user_funcPHP - 调用类,如 call_user_func
【发布时间】:2016-05-22 12:13:01
【问题描述】:

我有 2 个变量:

$class : contains the name of the class
$params : contains the parameters to initialize the class like ["key1" => "value1", "key2" => "value2"]

我想调用一个类,比如函数 call_user_func() 用函数做的事情

即:

$classObject = call_class($class, $params);
// Do the same that: 
$classObject = new $class("value1", "value2");

【问题讨论】:

    标签: php class call


    【解决方案1】:

    如果您运行的是 PHP >= 5.6,一个选项是使用数组参数解包:

    $classObject = new $class(...$params);
    

    另一个是使用Reflection

    $reflection = new ReflectionClass($class);
    $classObject = $reflection->newInstanceArgs($params);
    

    【讨论】:

      【解决方案2】:

      call_user_func_array 允许您调用类方法。

      <?php
      
      class Foo {
        public function bar($param1, $param2) {
          echo $param1.$param2;
        }
      }
      
      $className = 'Foo';
      
      call_user_func_array(array(new $className, 'bar'), array('Hello', 'World !'));
      

      【讨论】:

      • 你的答案是对的,但马克贝克的答案是 OOP
      • @ClémentLaffitte 同意。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-06-30
      • 1970-01-01
      • 2012-07-31
      • 2010-09-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多