PHP function error

My validation function looks like

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

Function Call Example

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

As you can see, my validate function has 3 input vars. I don’t often use the second var - $ data2, so I set it to 0 by default. But when I call this function as an example (as far as I know, it means $ data = $ lname, $ data2 = 0, $ type = 'name ') receiving an error message

 Missing argument 3 ($type) for validate() 

How can i fix this?

+6
source share
4 answers

Missing argument 3 (type $) for validate ()

Always include optional arguments as final arguments. Since PHP has no named parameters and does not "overload ala Java", this is the only way:

 function validate($data, $type, $data2 = 0) { } 
+19
source

You should at least set the type to $ 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 allows you to set a value for parameters, but you cannot define a parameter WITHOUT a given value AFTER a parameter that HAVE the set value. Therefore, if you need to always specify the third parameter, you need to switch the second and third as follows:

 function validate($data, $type, $data2 = 0) 
+6
source

From http://php.net/manual/en/functions.arguments.php

Note that when using the default arguments, any default values ​​must be on the right side of any arguments other than the default; otherwise everything will not work as expected

You must switch the second and third arguments to the function, making the optional argument last. So it is done:

 function validate($data, $type, $data2 = 0) { .... 
0
source
 function validate($data, $data2, $data3, $data4, $data5) 

im a newbie but i think you can use a thousand arguments if you call so

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

Source: https://habr.com/ru/post/901114/


All Articles