Search code examples
phpfunctionargument-passingoptional-parametersdefault-arguments

How to make function argument optional in PHP?


Suppose following is my function definition:

public function addPhotoFeed($val)
{
-----------------------------
------------------------------
-----------------------------
}

In above function $val is an array that is passed as an argument to the same.

Now I want to call the above function when I don't pass any argument. So how should I call it?


Solution

  • Simply assign the parameter to null, so like this.

    public function addPhotoFeed($val = null)
    {
     //TODO
    }
    

    You will be able to call the function with or without parameters

    addPhotoFeed();
    addPhotoFeed("Something");
    

    If you don't want the function to do anything when its called with a null parameter, then you could add a condition inside the function, something like this.

    public function addPhotoFeed($val = null)
    {
       if($vall == null)
         // Do nothing
       else
         // Do something
    }