从PHP的变量参数调用构造函数 [英] Call a constructor from variable arguments with PHP

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

问题描述

我有一个接受变量参数的函数,我从 func_get_args()获得。



需要调用具有这些参数的构造函数。



使用 call_user_func ,您可以使用数组调用函数的参数,但是如何从它调用构造函数呢?我不能只是传递参数数组;

解决方案



对于PHP< 5.3如果不先用 call_user_func_array 创建一个类的实例,就不容易做到。但是, 反射 这很不重要:

  $ reflection = new ReflectionClass('yourClassName'); 
$ instance = $ reflection-> newInstanceArgs($ yourArrayOfConstructorArguments);


I have a function that takes variadic arguments, that I obtain from func_get_args().

This function needs to call a constructor with those arguments. However, I don't know how to do it.

With call_user_func, you can call functions with an array of arguments, but how would you call a constructor from it? I can't just pass the array of arguments to it; it must believe I've called it "normally".

Thank you!

解决方案

For PHP < 5.3 it's not easily doable without first creating an instance of the class with call_user_func_array. However with Reflection this is pretty trivial:

$reflection = new ReflectionClass( 'yourClassName' );
$instance = $reflection->newInstanceArgs( $yourArrayOfConstructorArguments );

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

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