How to Create Optional Arguments in PHP

How do you create optional arguments in php?

Much like the manual, use an equals (=) sign in your definition of the parameters:

function dosomething($var1, $var2, $var3 = 'somevalue'){
// Rest of function here...
}

Optional Parameter

You must declare a parameter optional in the function parameters. It doesn't work because you have to told the PHP interpreter to expect a parameter.

function myFunc($param, $optional = null){
// ...
}

In PHP 7+ you can use the spread operator for argument unpacking to denote optional parameters. This is better than sending an array of arguments to a function.

function myFunc($param, ...$optional){
print_r($optional);
}

myFunc('baz'); // Array ( )
myFunc('baz', 'foo', 'foobar', 'whoo'); // Array ( [0] => foo [1] => foobar [2] => whoo )

PHP Function with Optional Parameters

Make the function take one parameter: an array. Pass in the actual parameters as values in the array.


Edit: the link in Pekka's comment just about sums it up.

How can I make an optional argument in my custom function in PHP?

Optional arguments need to be given a default value. Instead of checking isset on the argument, just give it the value you want it to have if not given:

function dummy_func($optional = "World!")
{
$output = "Hello " . $optional;
return $output;
}

See the page on Function arguments in the manual (particularly the Default argument values section).

Optional parameters in PHP function without considering order

This is modified from one of the answers and allows arguments to be added in any order using associative arrays for the optional arguments

 function createUrl($host, $path, $argument = []){
$optionalArgs = [
'protocol'=>'http',
'port'=>80];
if( !is_array ($argument) ) return false;
$argument = array_intersect_key($argument,$optionalArgs);
$optionalArgs = array_merge($optionalArgs,$argument);
extract($optionalArgs);
return $protocol.'://'.$host.':'.$port.'/'.$path;
}



//No arguments with function call
echo createUrl ("www.example.com",'no-arguments');
// returns http://www.example.com:80/no-arguments

$argList=['port'=>9000];
//using port argument only
echo createUrl ("www.example.com",'one-args', $argList);
//returns http://www.example.com:9000/one-args

//Use of both parameters as arguments. Order does not matter
$argList2 = ['port'=>8080,'protocol'=>'ftp'];
echo createUrl ("www.example.com",'two-args-no-order', $argList2);
//returns ftp://www.example.com:8080/two-args-no-order

How do I add optional arguments to my function?

You can specify a default value for your arguments:

function foo($arg1, $optional_arg2 = NULL)
{
// ...
}

$optional_arg2 = NULL specifies that if not given when the function is called, $optional_arg2 will be NULL. The default value of an argument can be a scalar value (string, number or boolean), an array, or NULL, but it cannot be a variable, class member or function call.

Passing an optional parameter in PHP Function

try this:

function test($required, $optional = NULL){..} 

then you can call

test($required, $optional)

and with $optional null

test($required);  

How to make function argument optional in PHP?

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
}

How do I pass specific optional arguments?

You can have optional arguments in PHP, but you cannot have either/or arguments as that would require function overloading which is not supported in PHP. Given your example, you must call the constructor as follows:

// How do I pass specific arguments here?
$case_1 = new User("Bob", null, 34);
$case_2 = new User("James", "m");

If you want to eliminate the optional but required to be null argument, you will need to get clever.

Option One: Use a factory. This would require a common argument constructor in conjunction with mutator methods for each of the unique arguments.

class UserFactory {
public static function createWithGender($name, $gender)
{
$user = new User($name);
$user->setGender($gender);

return $user;
}

public static function createWithAge($name, $age)
{
$user = new User($name);
$user->setAge($age);

return $user;
}
}

$case_1 = UserFactory::createWithAge("Bob", 34);
$case_2 = UserFactory::createWithGender("James", "m");

The factory doesn't need to be a separate class, you can alternatively add the static initializers to the User class if desired.

class User {
function __construct($name = null)
{
...
}

public static function createWithGender($name, $gender)
{
$user = new static($name);
$user->setGender($gender);

return $user;
}

public static function createWithAge($name, $age)
{
$user = new static($name);
$user->setAge($age);

return $user;
}
}

$case_1 = User::createWithAge("Bob", 34);
$case_2 = User::createWithGender("James", "m");

Option Two: Do some argument detection. This will only work if the arguments are all unique types.

class User {
public function __construct($name, $second = null) {
if (is_int($second)) {
$this->age = $second;
} else {
$this->gender = $second;
}
}
}

$case_1 = new User("Bob", 34);
$case_2 = new User("James", "m");

PHP optional parameter

That's because the $param = 'value' bit in the function declaration is not executed every time the function is called.

It only comes into play if you don't pass a value for that parameter.

Instead of reading it as a literal assignment PHP does something along the lines of the following under the hood whenever it enters your function.

if true === $param holds no value
$param = 'value'
endif

In other words, $param = 'value' is not a literal expression within the context of the language but rather a language construct to define the desired behaviour of implementing fallback default values.

Edit: Note that the snippet above is deliberately just pseudo code as it's tricky to accurately express what's going using PHP on once PHP has been compiled. See the comments for more info.



Related Topics



Leave a reply



Submit