3.1 PHP Functions
3.1 PHP Functions
PHP Functions
Dr. Charles Severance
www.wa4e.com
WEB APPLICATIONS
PHP Functions FOR EVERYBODY
Why Functions?
• PHP has lots of built-in functions that we use all the time.
• We write our own functions when our code reaches a
certain level of complexity.
WEB APPLICATIONS
PHP Functions FOR EVERYBODY
• Don t repeat yourself - make it work once and then reuse it.
Built-In Functions...
• Much of the power of PHP comes from its built-in functions.
function greet() {
print "Hello\n"; Hello
} Hello
greet();
greet();
WEB APPLICATIONS
PHP Functions FOR EVERYBODY
• Case does not matter – but please do not take advantage of this
WEB APPLICATIONS
PHP Functions FOR EVERYBODY
Return Values
Often a function will take its arguments, do some computation, and
return a value to be used as the value of the function call in the calling
expression. The return keyword is used for this.
function greeting() {
return "Hello"; Hello Glenn
} Hello Sally
Arguments
Functions can choose to accept optional arguments. Within the function
definition the variable names are effectively “aliases” to the values passed in
when the function is called.
function howdy($lang) {
if ( $lang == 'es' ) return "Hola"; Hola Glenn
if ( $lang == 'fr' ) return "Bonjour";
return "Hello"; Bonjour Sally
}
Optional Arguments
Arguments can have defaults, and so can be omitted.
function howdy($lang='es') {
if ( $lang == 'es' ) return "Hola";
if ( $lang == 'fr' ) return "Bonjour";
return "Hello"; Hola Glenn
} Bonjour Sally
print howdy() . " Glenn\n";
print howdy('fr') . " Sally\n";
WEB APPLICATIONS
PHP Functions FOR EVERYBODY
Call By Value
• The argument variable within the function is an “alias” to the actual
variable.
• But even further, the alias is to a *copy* of the actual variable in the
function call.
function double($alias) {
$alias = $alias * 2; Value = 10 Doubled = 20
return $alias;
}
$val = 10;
$dval = double($val);
echo "Value = $val Doubled = $dval\n";
WEB APPLICATIONS
PHP Functions FOR EVERYBODY
Call By Reference
Sometimes we want a function to change one of its arguments, so we
indicate that an argument is “by reference” using ( & ).
function triple(&$realthing) {
$realthing = $realthing * 3; Triple = 30
}
$val = 10;
triple($val);
echo "Triple = $val\n";
WEB APPLICATIONS
PHP Functions FOR EVERYBODY
http://php.net/manual/en/function.sort.php
WEB APPLICATIONS
PHP Functions FOR EVERYBODY
Acknowledgements / Contributions
These slides are Copyright 2010- Charles R. Severance (www.dr- Continue new Contributors and Translators here
chuck.com) as part of www.wa4e.com and made available under a
Creative Commons Attribution 4.0 License. Please maintain this
last slide in all copies of the document to comply with the
attribution requirements of the license. If you make a change, feel
free to add your name and organization to the list of contributors
on this page as you republish the materials.