将可变数量的变量传递给 PHP 中的类 [英] Pass variable number of variables to a class in PHP

查看:33
本文介绍了将可变数量的变量传递给 PHP 中的类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要传递可变数量的字符串来实例化不同的类.我总是可以对数组的大小进行切换:

I need to pass a variable number of strings to instantiate different classes. I can always do a switch on the size of the array:

switch(count($a)) {
case 1:
    new Class(${$a[0]});
    break;
case 2:
    new Class(${$a[0]}, ${$a[1]});
    break;
etc...

必须有更好的方法来做到这一点.如果我有一个字符串数组(variable1"、variable2"、variable3"、...),我如何在不手动考虑所有可能性的情况下实例化一个类?

There has to be a better way to do this. If I have an array of strings ("variable1", "variable2", 'variable3", ...), how can I instantiate a Class without manually accounting for every possibility?

推荐答案

如果一定要这样做,可以试试:

If you must do it this way, you can try:

$variable1 = 1;
$variable2 = 2;
$variable3 = 3;
$variable4 = 4;

$varNames = array('variable1', 'variable2', 'variable3', 'variable4');
$reflection = new ReflectionClass('A');
$myObject = $reflection->newInstanceArgs(compact($varNames)); 

class A
{
    function A()
    {
        print_r(func_get_args());
    }
}

这篇关于将可变数量的变量传递给 PHP 中的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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