Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why interpreter not giving error for the first code [duplicate]

Tags:

php

Following code is very simple, but why PHP is allowing a function to be called with n number of arguments?

<?php

    function ab(){
        echo "yes";
    }

    ab(2);
?>

//output
yes

However following code giving Warning: Missing argument 2 for ab(), but still giving output

<?php
    function ab($a, $b){
        echo "yes";
    }

    ab(2);
?>

//output
yes

I know that this warning is ok but my question is about the first code.

like image 821
Vijay Dohare Avatar asked Sep 18 '25 19:09

Vijay Dohare


1 Answers

I can give you the answer to may way and this is the simple way because no any person have still give the answer. (I appreciate if someone give the answer in better way better than me.)

Well, according to me as I understood by this link.

As per your question and this is the general thing we can see that you have defined two parameters and you are calling out with one parameter.

The Warning you are getting because this function is making you attention what you are doing wrong.

When you call this function, it will give you the runtime warning and very likely to cause errors.

As this is not the fatal errors so, the execution of the script is not halted.

And as the execution of the script is not halted, will give you the output with warning.

UPDATED:

As you questioned, will try to give my best for the answer.

The function (function ab($a, $b)) will initialize the variable but at the runtime will not check for the initiation.

The function count the number of parameters itself. When you call the function less than the number of parameter which you have defined in the function, will give you the warning. (Warning: Missing argument 2 for ab())

<?php
    function ab($a, $b){
        echo "yes";
    }

    ab(2);
?>

Now, if you pass the parameters more than the defined parameters, will not give you any warning because it satisfied with the (two) parameters.

<?php
    function ab($a, $b){
        echo "yes";
    }

    ab(1,2,3,4,5);
?>

Here, I can have only this answer as I tried my best. Hope you understood. Thanks.

like image 97
Virb Avatar answered Sep 20 '25 11:09

Virb