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 trialGreg Kaleka
39,021 PointsIs a default value of Null necessary?
Here's the code used in the video:
<?php
function get_info($name, $title = Null){
if($title){
echo "$name has arrived. They are with us as a $title.";
} else {
echo "$name has arrived. They have no title.";
}
}
get_info("Mike");
?>
Works great. However, it occurred to me that setting a default value of Null
is kind of silly, since leaving out the second parameter would set it to Null
anyway. I tried the code below (without the = Null
) and it worked exactly the same. Any reason why this might not be a best practice?
<?php
function get_info($name, $title){
if($title){
echo "$name has arrived. They are with us as a $title.";
} else {
echo "$name has arrived. They have no title.";
}
}
get_info("Mike");
?>
Greg Kaleka
39,021 PointsOK makes sense. Thanks!
1 Answer
miguelcastro2
Courses Plus Student 6,573 PointsBy setting the $title variable to NULL you give it a default value and do not need to provide a $title in your function call. If you do not set a default value then your code will generate a warning and you may not see the warning on screen if you did not set error reporting ON. However, you will definitely see the error in your server log files. The practice of setting default values for optional function arguments is a good practice.
Rebecca Vonada
5,274 PointsRebecca Vonada
5,274 PointsIt looks like, in this case, the null exists to clear the variable -- so if you were applying this function to, say, data from a form that included input where title would be, it would be set to null. My guess is that you'd be removing the =null later or your if statement wouldn't be very useful, but for now it ensures a consistent outcome when you use your function.
If you want to test it, you can try running
get_info("Mike", "Mr.");
with and without $title = null to see the difference in how it runs.