Syntax for default parameters in PHP functions

Source: Internet
Author: User

function can define C + +the default values for the style scalar parameters are as follows: Example#3 Using default parameters in functions<?PHPfunctionMakecoffee ($type= "Cappuccino"){    return"Making a cup of$type. \ n ";}EchoMakecoffee ();EchoMakecoffee (NULL);EchoMakecoffee ("Espresso");?>The above routines will output: Making a cup of cappuccino.Making a cup of.Making a cup of espresso.PHP also allows the use of arraysArrayand special typesNULLas the default parameter, for example: Example#4 Using non-scalar types as default parameters<?PHPfunctionMakecoffee ($types=Array("Cappuccino"),$coffeeMaker=NULL){    $device=Is_null($coffeeMaker) ? "Hands":$coffeeMaker; return"Making a cup of".Join(", ",$types). "With$device. \ n ";}EchoMakecoffee ();EchoMakecoffee (Array("Cappuccino", "Lavazza"), "teapot");?>The default value must be a constant expression, not such as a variable, a class member, or a function call. Note When you use the default parameters, any default arguments must be placed to the right of any non-default parameters, otherwise the function will not work as expected. Consider the following code snippet: Example#5 Incorrect usage of function default parameters<?PHPfunctionMakeyogurt ($type= "Acidophilus",$flavour){    return"Making a bowl of$type $flavour. \ n ";}EchoMakeyogurt ("Raspberry");//won ' t work as expected?>The above routines will output: Warning: Missing argument 2In the Makeyogurt () in/usr/local/etc/httpd/htdocs/phptest/functest.html on line 41Making a bowl of raspberry.now, compare the above example and this example: Example#6 Proper usage of function default parameters<?PHPfunctionMakeyogurt ($flavour,$type= "Acidophilus"){    return"Making a bowl of$type $flavour. \ n ";}EchoMakeyogurt ("Raspberry");//works as expected?>The above routines will output: Making a bowl of acidophilus raspberry.Note: The referenced parameters can also have default values since PHP 5.

Syntax for default parameters in PHP functions

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.