Reputation: 23189
<?php
/* Copyright Date
--------------------------*/
function copyright_date($creation_year) {
$current_year = date('Y');
if ($creation_year == $current_year || $creation_year == '') {
echo $current_year;
}
else {
echo $creation_year . '-' . $current_year;
}
}
?>
If someone forgets to add the argument (the year the website was created), e.g.
<?php copyright_date(); ?>
instead of:
<?php copyright_date(2009); ?>
how would I test to see if the argument was left blank? In my if statement, that's what $creation_year == '' is for, but since the argument isn't a string, it doesn't work.
Upvotes: 1
Views: 2950
Reputation: 330
Actually I think you MUST use func_num_args()
. It's much more safer in practice.
function copyright_date($creation_year = NULL) {
if(!func_num_args()) {
// Nothing passed to the function
}
}
why? Because if you set a default value, let's say function copyright_date($creation_year = NULL)
you wouldn't know if NULL is passed. Also isset()
returns true
if you set a default value.
Upvotes: 2
Reputation: 25
If anyone needs additional clarification on the answer:
You can try to set a function's parameters to NULL. This will set the value of the variable (in your case $creation_year) to an empty variable. The variable has been declared, but contains no value. When the function is called like so:
<?php copyright_date(); ?>
Your function will execute the code in the else block.
If the function is called the other way (with argument supplied), like so:
<?php copyright_date($creation_year); ?>
The argument supplied replaces the the NULL value, and the code in the If block is run.
Considering this, you also need to have this :
|| $creation_year == NULL
In your if condition. This will check if the value of $creation_year is empty.
Upvotes: 0
Reputation: 176753
Make $creation_year
an optional argument with a default value of NULL
.
function copyright_date($creation_year=NULL) {
Now inside the function just test if $creation_year
is equal to NULL
, which will happen when the function is called with no arguments.
Upvotes: 4
Reputation: 827832
You could use the isset
function
if ($creation_year == $current_year || !isset($creation_year)){
//...
}
Upvotes: 0