Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP function missing argument error

My validate function looks like that

function validate($data, $data2 = 0, $type)
{
...

Function call example

if ($result = validate($lname, 'name') !== true)
        response(0, $result, 'lname');

As you see, my validate function has 3 input vars. I'm not using second var - $data2 often, that's why set it to 0 by default. But when I'm calling this function as given example (as far as I know it means $data=$lname, $data2=0, $type='name') getting error message

Missing argument 3 ($type) for validate() 

How can I fix that?

like image 715
Tural Ali Avatar asked Nov 09 '11 12:11

Tural Ali


People also ask

How to pass arguments in PHP function?

PHP Function Arguments Information can be passed to functions through arguments. An argument is just like a variable. Arguments are specified after the function name, inside the parentheses. You can add as many arguments as you want, just separate them with a comma.

What is missing argument?

The missing argument is an object that triggers an error if and only if it is the result of evaluating a symbol. No error is produced when a function call evaluates to the missing argument object.

What is missing parameters in php?

The default value is used for any missing arguments in PHP 7. x versions. In PHP 8, we can pass the arguments to a function based on the parameter name, rather than passing the parameter position. Order doesn't matter in PHP 8, it is allowed to skip default values randomly and it is also self-documenting.

How to set default value in PHP function?

Setting Default Values for Function parameterPHP allows us to set default argument values for function parameters. If we do not pass any argument for a parameter with default value then PHP will use the default set value for this parameter in the function call. Example: PHP.


2 Answers

Missing argument 3 ($type) for validate()

Always list optional arguments as the last arguments. Since PHP doesn't have named parameters nor "overloading ala Java", that's the only way:

function validate($data, $type, $data2 = 0) {
}
like image 82
Berry Langerak Avatar answered Oct 10 '22 01:10

Berry Langerak


You should at least set the $type in this line:

function validate($data, $data2 = 0, $type)

at NULL or '' as you can see here:

function validate($data, $data2 = 0, $type = null)

PHP let you to set a value for the parameters, but you can't define a parameter WITHOUT a preset value AFTER parameter(s) which HAVE a preset value. So if you need to always specify the third param, you have to switch the second and the third like this:

function validate($data, $type, $data2 = 0)
like image 40
Aurelio De Rosa Avatar answered Oct 10 '22 00:10

Aurelio De Rosa