Default parameters

When designing your functions, it is often helpful to be able to assign default values for parameters that aren't passed - PHP does this for most of its functions, and it saves you having to pass in parameters most of the time if they are usually the same.

To define your own default parameters for a function, simply add the constant value you would like them set to after the variables, like this:

<?php
    function doFoo($Name = "Paul") {
        return "Foo $Name!\n";
    }

    doFoo();
    doFoo("Paul");
    doFoo("Andrew");
?>

That script will output the following:

Foo Paul!
Foo Paul!
Foo Andrew!

Now, consider this function:

function doBar($FirstName, $LastName = "Smith") { }

Does that mean that both $FirstName and $LastName are set to Smith? As it happens, it is only $LastName - PHP treats the two variables as functionally independent of each other, which means you can use code like this:

function doBar($FirstName = "John", $LastName = "Smith") {
    return "Hello, $FirstName $LastName!\n";
}

So, to greet someone called John Smith, you could just use this:

doBar();

To greet someone called Tom Davies, you would use this:

doBar("Tom", "Davies");

To greet someone called Tom Smith, you would use this:

doBar("Tom");

Now, how would you greet someone called John Wilson? Ideally you would let PHP fill in the first parameter for you, as John is the default for the function, and you would provide the Wilson part. But if you try code like this, you will see it does not work:

doBar("Wilson");

Instead of John Wilson you will get Wilson Smith - PHP will assume the parameter you provided was for the first name, as it fills its parameters from left to right. The same logic dictates that you cannot put a default value before a non-default value, like this:

function doWombat($FirstName = "Joe", $LastName) { }

If someone used doWombat("Peter"), would they be trying to provide a value for $FirstName to use instead of the default, or do they want the default value in there and Peter was for $LastName? Hopefully you can see why PHP will flag up an error if you attempt this!

 

Want to learn PHP 7?

Hacking with PHP has been fully updated for PHP 7, and is now available as a downloadable PDF. Get over 1200 pages of hands-on PHP learning today!

If this was helpful, please take a moment to tell others about Hacking with PHP by tweeting about it!

Next chapter: Variable parameter counts >>

Previous chapter: Returning by reference

Jump to:

 

Home: Table of Contents

Copyright ©2015 Paul Hudson. Follow me: @twostraws.