Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

PHP PHP Functions Introducing Functions PHP Function Default Arguments

Nathan Richie
Nathan Richie
1,428 Points

Question about passing default values and what it says in PHP docs.

Specifically with example 5 and 6 on this page: http://us3.php.net/manual/en/functions.arguments.php

It says all default arguments should be to the right of non default arguments. But when i tested it in the workspace it worked both ways. Has that changed since PHP5-7?

Thanks

Nathan Richie
Nathan Richie
1,428 Points

NVM figured it out. That is only the case if you aren't passing all the possible arguments to the function.

Example:

This throws an error:

function get_info($title= Null, $name) { if($title) { echo "$name has arrived, they are with us as a $title"; } else { echo "$name has arrived, welcome!"; }

}

get_info('Nate');

THIS DOES NOT:

function get_info($title= Null, $name) { if($title) { echo "$name has arrived, they are with us as a $title"; } else { echo "$name has arrived, welcome!"; }

}

get_info('Wizard','Nate');

But it's a good habit to always write it like this:

function get_info($name, $title= Null)

Am I correct in my reasoning?

1 Answer

That is the correct reasoning!

<?php
function get_info($title= Null, $name) { 
    if($title) {
        echo "$name has arrived, they are with us as a $title"; 
    } 
    else {
        echo "$name has arrived, welcome!"; 
    }
}

get_info('Nate');
?>

The reason this won't work is that $name is never defined due to how the function is read. In this case, title would get defined, but not $name, since the function reads variables from left to right. If you define $name (like so: get_info('Title', 'Nate')) it will work, because $name is defined. However it's frowned upon to use 'required' variables after 'non-required' variables since this can lead to confusion.