T
T
Tiradoir2010-11-11 19:41:41
PHP
Tiradoir, 2010-11-11 19:41:41

How to find out with standard PHP tools whether arguments are required to call a method?

I am writing my bike for experience, the routing is done as in CI:
CodeIgniter uses an approach based on address segments :
www.your-site.com/news/article/my_article
are built like this:
www.your-site.com/class/function/arg
The first segment describes the class controller that is accessed.
In the second segment, there is a reference to the function function or method to be called.
The third and subsequent segments describe the variables that will be passed to this function.
In CI, a method might look like this:
function hello ($name, $id) {
echo "\$name = $name";
echo "
";
echo "$id";
}
Now the question is, in cases where one of the arguments for the method was not passed to the url, an error naturally occurs.
How can I check how many arguments are required to call the method? You need to check before calling, so func_num_args will not work use.Or
maybe another way out of the situation, tell me?Thank you very much in advance.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
M
m00t, 2010-11-11
@m00t

php.net/manual/en/book.reflection.php

function test_function($param1, $param2 = NULL)
{
  echo $param1;
}

$ref_function = new ReflectionFunction('test_function');

foreach($ref_function->getParameters() as $param)
{
  var_dump($param->isOptional());
}

var_dump($ref_function->getNumberOfRequiredParameters());

will output:
bool(false)
bool(true)
int(1)

M
MyraJKee, 2010-11-11
@MyraJKee

In my opinion, it is better to catch errors at the function level, like:

function my_action($param1 = null, $param2 = null) {
if($param1 === null) {
throw new Exception('');
}
}

Y
Yuri, 2010-11-12
@yul

Have you watched how CI is done?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question