When creating a function that takes arguments, you can set default values for it: function function_name($argument2, $argument = 6){ statements } Why would you want to set default values in a function? Well, if you are for example writing a program that involves calculating tax, which does not change often but does change sometimes, a function like this would be appropriate. It allows the assumption of a value, but still permits you to change the value when needed. The default value is overwritten when you specify a value, otherwise the value will stay the same. For example, let's create a new function that will take your age, first name and last name: function mydetails($firstname, $lastname, $age=23){ echo "My name is " .$firstname. " " .$lastname. " and I am } To call this function, type: mydetails(34,'John','Doe') And the result will be... My name is John Doe and I am 34 years old As you can see, the default value of 23 has been overwritten to 34. If, for example, you call this function without the $age argument, the function will assume that $firstname is the first argument. In other words, it will replace $age with $firstname and $firstname with $lastname. In that case, when you call this function, the results will be: My name is Doe and I am John years old. Just make sure that you write the default values after the other standard values (the arguments without defaults): function mydetails($firstname, $lastname, $age=23){ echo "My name is " .$firstname. " " .$lastname. " and I am } This is because PHP assigns the values directly to the arguments as they are received from the call line.
blog comments powered by Disqus |
|
|
|
|
|
|
|