我有一个带有两个参数的函数:
function index($LoadFunction, $footer) {
// My statements
}
我可以获得发送到此函数的参数总数,如index(1,2,3,4)
$numargs = func_num_args();
echo "Number of arguments: $numargs\n";
我想知道我可以向这个index()
函数发送多少个参数。
我将如何做到这一点。
EDIT1:
我也尝试过这些,但这并不能回应任何事情
https://stackoverflow.com/a/346789/1182021
https://stackoverflow.com/a/346943/1182021
EDIT2:
好的,我会以更合适的方式解释它:
class foo { function bar ( arg1, arg2 ){ ..... } }
我这样打电话给foo
课:
$class = new foo(); // Instantiating my class $class->bar(1,2); // This piece of code is fine
现在我想做的是:
$method = new ReflectionClass('foo', 'bar'); $num = $method->getNumberOfParameters(); // Ideally this should give me total number of arguments which this 'bar' // function can take, but it won't echo anything.
所以我怎么能得到这个,我不想去检查它:I want to check it before executing the function.
我如何使用这个东西:
ReflectionFunctionAbstract::getNumberOfParameters — Gets number of parameters ReflectionFunctionAbstract::getNumberOfRequiredParameters — Gets number of required parameters
答案 0 :(得分:1)
争论的数量几乎无穷无尽。限制不取决于语言本身,而是取决于硬件/操作系统限制,如内存使用和类似的东西。所以你可能不会遇到会导致任何问题的情况。
你也可以代替无穷无尽的参数列表,只是将数组作为参数传递,这本身也可以实际上包含无穷无尽的键/值对列表。在资源使用方面不会有很大的不同,但我个人觉得当参数列表可能真的很长时,它更容易处理。
- 编辑
如果我理解你想做什么(但如果我不这样做,请更清楚地解释一下),这就是你想要的:
function my_function($arg1, $arg2) {
if(func_num_args() > 2) {
throw new ErrorException('Maximum number of arguments exceeded');
// OR: trigger_error('Maximum number of arguments exceeded', E_USER_ERROR);
}
echo 'You are inside "my_function()" and have passed exactly 2 arguments';
}
执行此操作时:
my_function('some value', 'another value');
它回应:You are inside "my_function()" and have passed exactly 2 arguments
但是当你执行这段代码时:
my_function('some value', 'another value', 'too much arguments...');
它会抛出异常(或触发错误,无论你选择什么)
- 编辑2
是的,我明白了;)
首先:您尝试在方法上使用ReflectionClass。您应该使用ReflectionFunction(用于过程函数)或ReflectionMethod(用于类方法)。
选项1:
function my_function($arg1, $arg2) {
// do something
}
$reflection = new ReflectionFunction('my_function');
echo 'Function "my_function" has '. $reflection->getNumberOfParameters() .' arguments';
选项2:
class MyClass {
function my_function($arg1, $arg2) {
// do something
}
}
$reflection = new ReflectionMethod('MyClass::my_function');
echo 'Class method MyClass::my_function() has '. $reflection->getNumberOfParameters() .' arguments';
您可以在两种情况下使用$reflection->getNumberOfRequiredParameters()
答案 1 :(得分:1)
PHP支持用户定义的可变长度参数列表 功能。这非常简单,使用func_num_args(), func_get_arg()和func_get_args()函数。
不需要特殊语法,参数列表可能仍然存在 显式提供函数定义,并将表现为 正常。
所以你可以将任意数量的参数传递给你的函数index(1,2,3,4,5,...)
在你的函数中,如果你没有传递至少2个参数,PHP就会生成一个警告。