在构造函数中使用可变数量的参数动态调用Class [英] Dynamically call Class with variable number of parameters in the constructor

查看:95
本文介绍了在构造函数中使用可变数量的参数动态调用Class的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道可以使用在这里找到的c​​all_user_func_array()来调用带有可变数量参数的函数->

I know that it is possible to call a function with a variable number of parameters with call_user_func_array() found here -> http://php.net/manual/en/function.call-user-func-array.php . What I want to do is nearly identical, but instead of a function, I want to call a PHP class with a variable number of parameters in it's constructor.

它可以像下面那样工作,但是我不知道参数的数量,所以我不知道如何实例化该类.

It would work something like the below, but I won't know the number of parameters, so I won't know how to instantiate the class.

<?php
//The class name will be pulled dynamically from another source
$myClass = '\Some\Dynamically\Generated\Class';
//The parameters will also be pulled from another source, for simplicity I
//have used two parameters. There could be 0, 1, 2, N, ... parameters
$myParameters = array ('dynamicparam1', 'dynamicparam2');
//The instantiated class needs to be called with 0, 1, 2, N, ... parameters
//not just two parameters.
$myClassInstance = new $myClass($myParameters[0], $myParameters[1]);

推荐答案

您可以使用ReflectionClass

You can do the following using ReflectionClass

$myClass = '\Some\Dynamically\Generated\a';
$myParameters = array ('dynamicparam1', 'dynamicparam2');

$reflection = new \ReflectionClass($myClass); 
$myClassInstance = $reflection->newInstanceArgs($myParameters); 

PHP手册: http://www.php.net/manual/zh/reflectionclass.newinstanceargs. php

在php 5.6中,您可以通过参数解压缩来实现. .

In php 5.6 you can achieve this with Argument unpacking.

$myClass = '\Some\Dynamically\Generated\a';
$myParameters = ['dynamicparam1', 'dynamicparam2'];

$myClassInstance = new $myClass(...$myParameters); 

这篇关于在构造函数中使用可变数量的参数动态调用Class的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆