SlideShare a Scribd company logo
PHP Functions / Modularity
Dr. Charles Severance
www.wa4e.com
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.
To function or not to function...
• Organize your code into “paragraphs” - capture a complete
thought and “name it”.
• Don’t repeat yourself - make it work once and then reuse it.
• If something gets too long or complex, break up logical
chunks and put those chunks in functions.
• Make a library of common stuff that you do over and over -
perhaps share this with your friends...
PHP Documentation - Google
PHP Documentation - Google
Built-In Functions...
• Much of the power of PHP comes from its built-in functions.
• Many are modeled after C string library functions (i.e.
strlen()).
echo strrev(" .dlrow olleH"); echo
str_repeat("Hip ", 2); echo
strtoupper("hooray!");
echo strlen("intro");
echo "n";
Hello world.
Hip Hip
HOORAY!
5
Defining Your Own Functions
We use the function keyword to define a function, we name the
function and take optional argument variables. The body of the
function is in a block of code { }
function greet() {
print "Hellon";
}
greet();
greet();
Hello
Hello
Choosing Function Names
• Much like variable names - but do not start with a dollar sign
• Start with a letter or underscore - consist of letters, numbers,
and underscores ( _ )
• Avoid built-in function names
• Case does not matter – but please do not take advantage of
this
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";
}
print greeting() . " Glennn";
print greeting() . " Sallyn";
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";
if ( $lang == 'fr' ) return "Bonjour";
return "Hello";
}
print howdy('es') . " Glennn";
print howdy('fr') . " Sallyn";
Hola Glenn
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";
}
print howdy() . " Glennn";
print howdy('fr') . " Sallyn";
Hola Glenn
Bonjour Sally
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;
return $alias;
}
$val = 10;
$dval = double($val);
echo "Value = $val Doubled = $dvaln";
Value = 10 Doubled = 20
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;
}
$val = 10;
triple($val);
echo "Triple = $valn";
Triple = 30
http://php.net/manual/en/function.sort.php
Scope and Modularity
Variable Scope
• In general, variable names used inside of function code do
not mix with the variables outside of the function to avoid
unexpected side effects if two programmers use the same
variable name in different parts of the code.
• We call this “name spacing” the variables. The function
variables are in one “name space” whilst the main variables
are in another “name space”.
http://php.net/manual/en/language.variables.scope.php
Normal Scope (isolated)
function tryzap() {
$val = 100;
}
$val = 10;
tryzap();
echo "TryZap = $valn";
TryZap = 10
http://php.net/manual/en/language.variables.superglobals.php
Except for $_GET
Global Scope (shared)
function dozap() {
global $val;
$val = 100;
}
$val = 10;
dozap();
echo "DoZap = $valn";
DoZap = 100
Use this wisely, young
Jedi...
Global Variables – Use Rarely
• Passing variable in as parameter
• Passing value back as return value
• Passing variable in by reference
• If you use global variables, use long names with nice
unique prefixes
global $LastOAuthBodyBaseString;
global $LAST_OAUTH_BODY_BASE_STRING;
Coping with Missing Bits
Sometimes, depending on the version or configuration of a
particular PHP instance, some functions may be missing. We can
check that...
if (function_exists("array_combine")){
echo "Function exists";
} else {
echo "Function does not exist";
}
This allows for evolution.
http://php.net/manual/en/function.array-key-exists.php
One Heck of a Function…
• PHP is a very configurable system and has lots of capabilities
that can be plugged in.
• The phpinfo() function prints out the internal configuration
capabilities of your particular PHP installation,
<?php
phpinfo();
?>
Programming in Multiple Files
Including Files in PHP
• include "header.php"; - Pull the file in here
• include_once "header.php"; - Pull the file in here unless it
has already been pulled in before
• require "header.php"; - Pull in the file here and die if it is
missing
• require_once "header.php"; - You can guess what this
means...
• These can look like functions - require_once("header.php");
https://github.com/csev/wa4e
http://www.wa4e.com/
<?php
require "top.php";
require "nav.php";
?>
<div id="container">
<h1>Web Applications...</h1>
.
.
.
</div>
<?php
require "foot.php";
index.php
<?php
require "top.php";
require "nav.php";
?>
<div id="container">
<iframeheight="4600" width="100%" frameborder="0"
marginwidth="0"marginheight="0" scrolling="auto"src="software.php">
</iframe>
</div>
<?php
require "foot.php";
install.php
Summary
• Built-in functions
• Making new functions
• Arguments - pass by value and pass by reference
• Including and requiring files
• Checking to see if functions are present
Acknowledgements / Contributions
These slides are Copyright 2010- Charles R. Severance
(www.dr-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.
Initial Development: Charles Severance, University of Michigan
School of Information
Insert new Contributors and Translators here including names
and dates
Continue new Contributors and Translators here

More Related Content

Similar to PHP-03-Functions.ppt

Php introduction with history of php
Php introduction with history of phpPhp introduction with history of php
Php introduction with history of php
pooja bhandari
 
Basics PHP
Basics PHPBasics PHP
Introduction To Php For Wit2009
Introduction To Php For Wit2009Introduction To Php For Wit2009
Introduction To Php For Wit2009
cwarren
 
Living With Legacy Code
Living With Legacy CodeLiving With Legacy Code
Living With Legacy Code
Rowan Merewood
 
05php
05php05php
Prersentation
PrersentationPrersentation
Prersentation
Ashwin Deora
 
PHP Basics and Demo HackU
PHP Basics and Demo HackUPHP Basics and Demo HackU
PHP Basics and Demo HackU
Anshu Prateek
 
MIND sweeping introduction to PHP
MIND sweeping introduction to PHPMIND sweeping introduction to PHP
MIND sweeping introduction to PHP
BUDNET
 
Php, mysq lpart1
Php, mysq lpart1Php, mysq lpart1
Php, mysq lpart1
Subhasis Nayak
 
Php mysql classes in navi-mumbai,php-mysql course provider-in-navi-mumbai,bes...
Php mysql classes in navi-mumbai,php-mysql course provider-in-navi-mumbai,bes...Php mysql classes in navi-mumbai,php-mysql course provider-in-navi-mumbai,bes...
Php mysql classes in navi-mumbai,php-mysql course provider-in-navi-mumbai,bes...
anshkhurana01
 
HackU PHP and Node.js
HackU PHP and Node.jsHackU PHP and Node.js
HackU PHP and Node.js
souridatta
 
Wt unit 4 server side technology-2
Wt unit 4 server side technology-2Wt unit 4 server side technology-2
Wt unit 4 server side technology-2
PUNE VIDYARTHI GRIHA'S COLLEGE OF ENGINEERING, NASHIK
 
Giới thiệu PHP 7
Giới thiệu PHP 7Giới thiệu PHP 7
Giới thiệu PHP 7
ZendVN
 
Php
PhpPhp
PSGI and Plack from first principles
PSGI and Plack from first principlesPSGI and Plack from first principles
PSGI and Plack from first principles
Perl Careers
 
Hsc IT 5. Server-Side Scripting (PHP).pdf
Hsc IT 5. Server-Side Scripting (PHP).pdfHsc IT 5. Server-Side Scripting (PHP).pdf
Hsc IT 5. Server-Side Scripting (PHP).pdf
AAFREEN SHAIKH
 
Functuon
FunctuonFunctuon
Functuon
NithyaNithyav
 
Functuon
FunctuonFunctuon
Functuon
NithyaNithyav
 
Php essentials
Php essentialsPhp essentials
Php essentials
sagaroceanic11
 
Training on php by cyber security infotech (csi)
Training on  php by cyber security infotech (csi)Training on  php by cyber security infotech (csi)
Training on php by cyber security infotech (csi)
Cyber Security Infotech Pvt. Ltd.
 

Similar to PHP-03-Functions.ppt (20)

Php introduction with history of php
Php introduction with history of phpPhp introduction with history of php
Php introduction with history of php
 
Basics PHP
Basics PHPBasics PHP
Basics PHP
 
Introduction To Php For Wit2009
Introduction To Php For Wit2009Introduction To Php For Wit2009
Introduction To Php For Wit2009
 
Living With Legacy Code
Living With Legacy CodeLiving With Legacy Code
Living With Legacy Code
 
05php
05php05php
05php
 
Prersentation
PrersentationPrersentation
Prersentation
 
PHP Basics and Demo HackU
PHP Basics and Demo HackUPHP Basics and Demo HackU
PHP Basics and Demo HackU
 
MIND sweeping introduction to PHP
MIND sweeping introduction to PHPMIND sweeping introduction to PHP
MIND sweeping introduction to PHP
 
Php, mysq lpart1
Php, mysq lpart1Php, mysq lpart1
Php, mysq lpart1
 
Php mysql classes in navi-mumbai,php-mysql course provider-in-navi-mumbai,bes...
Php mysql classes in navi-mumbai,php-mysql course provider-in-navi-mumbai,bes...Php mysql classes in navi-mumbai,php-mysql course provider-in-navi-mumbai,bes...
Php mysql classes in navi-mumbai,php-mysql course provider-in-navi-mumbai,bes...
 
HackU PHP and Node.js
HackU PHP and Node.jsHackU PHP and Node.js
HackU PHP and Node.js
 
Wt unit 4 server side technology-2
Wt unit 4 server side technology-2Wt unit 4 server side technology-2
Wt unit 4 server side technology-2
 
Giới thiệu PHP 7
Giới thiệu PHP 7Giới thiệu PHP 7
Giới thiệu PHP 7
 
Php
PhpPhp
Php
 
PSGI and Plack from first principles
PSGI and Plack from first principlesPSGI and Plack from first principles
PSGI and Plack from first principles
 
Hsc IT 5. Server-Side Scripting (PHP).pdf
Hsc IT 5. Server-Side Scripting (PHP).pdfHsc IT 5. Server-Side Scripting (PHP).pdf
Hsc IT 5. Server-Side Scripting (PHP).pdf
 
Functuon
FunctuonFunctuon
Functuon
 
Functuon
FunctuonFunctuon
Functuon
 
Php essentials
Php essentialsPhp essentials
Php essentials
 
Training on php by cyber security infotech (csi)
Training on  php by cyber security infotech (csi)Training on  php by cyber security infotech (csi)
Training on php by cyber security infotech (csi)
 

Recently uploaded

BBR 2024 Summer Sessions Interview Training
BBR  2024 Summer Sessions Interview TrainingBBR  2024 Summer Sessions Interview Training
BBR 2024 Summer Sessions Interview Training
Katrina Pritchard
 
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdfবাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
eBook.com.bd (প্রয়োজনীয় বাংলা বই)
 
How to Setup Warehouse & Location in Odoo 17 Inventory
How to Setup Warehouse & Location in Odoo 17 InventoryHow to Setup Warehouse & Location in Odoo 17 Inventory
How to Setup Warehouse & Location in Odoo 17 Inventory
Celine George
 
BÀI TẬP BỔ TRỢ TIẾNG ANH LỚP 9 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2024-2025 - ...
BÀI TẬP BỔ TRỢ TIẾNG ANH LỚP 9 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2024-2025 - ...BÀI TẬP BỔ TRỢ TIẾNG ANH LỚP 9 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2024-2025 - ...
BÀI TẬP BỔ TRỢ TIẾNG ANH LỚP 9 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2024-2025 - ...
Nguyen Thanh Tu Collection
 
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
National Information Standards Organization (NISO)
 
writing about opinions about Australia the movie
writing about opinions about Australia the moviewriting about opinions about Australia the movie
writing about opinions about Australia the movie
Nicholas Montgomery
 
Walmart Business+ and Spark Good for Nonprofits.pdf
Walmart Business+ and Spark Good for Nonprofits.pdfWalmart Business+ and Spark Good for Nonprofits.pdf
Walmart Business+ and Spark Good for Nonprofits.pdf
TechSoup
 
Hindi varnamala | hindi alphabet PPT.pdf
Hindi varnamala | hindi alphabet PPT.pdfHindi varnamala | hindi alphabet PPT.pdf
Hindi varnamala | hindi alphabet PPT.pdf
Dr. Mulla Adam Ali
 
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
GeorgeMilliken2
 
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Dr. Vinod Kumar Kanvaria
 
Liberal Approach to the Study of Indian Politics.pdf
Liberal Approach to the Study of Indian Politics.pdfLiberal Approach to the Study of Indian Politics.pdf
Liberal Approach to the Study of Indian Politics.pdf
WaniBasim
 
How to Create a More Engaging and Human Online Learning Experience
How to Create a More Engaging and Human Online Learning Experience How to Create a More Engaging and Human Online Learning Experience
How to Create a More Engaging and Human Online Learning Experience
Wahiba Chair Training & Consulting
 
Présentationvvvvvvvvvvvvvvvvvvvvvvvvvvvv2.pptx
Présentationvvvvvvvvvvvvvvvvvvvvvvvvvvvv2.pptxPrésentationvvvvvvvvvvvvvvvvvvvvvvvvvvvv2.pptx
Présentationvvvvvvvvvvvvvvvvvvvvvvvvvvvv2.pptx
siemaillard
 
Film vocab for eal 3 students: Australia the movie
Film vocab for eal 3 students: Australia the movieFilm vocab for eal 3 students: Australia the movie
Film vocab for eal 3 students: Australia the movie
Nicholas Montgomery
 
The Diamonds of 2023-2024 in the IGRA collection
The Diamonds of 2023-2024 in the IGRA collectionThe Diamonds of 2023-2024 in the IGRA collection
The Diamonds of 2023-2024 in the IGRA collection
Israel Genealogy Research Association
 
Wound healing PPT
Wound healing PPTWound healing PPT
Wound healing PPT
Jyoti Chand
 
The basics of sentences session 6pptx.pptx
The basics of sentences session 6pptx.pptxThe basics of sentences session 6pptx.pptx
The basics of sentences session 6pptx.pptx
heathfieldcps1
 
How to deliver Powerpoint Presentations.pptx
How to deliver Powerpoint  Presentations.pptxHow to deliver Powerpoint  Presentations.pptx
How to deliver Powerpoint Presentations.pptx
HajraNaeem15
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
Nguyen Thanh Tu Collection
 
Digital Artefact 1 - Tiny Home Environmental Design
Digital Artefact 1 - Tiny Home Environmental DesignDigital Artefact 1 - Tiny Home Environmental Design
Digital Artefact 1 - Tiny Home Environmental Design
amberjdewit93
 

Recently uploaded (20)

BBR 2024 Summer Sessions Interview Training
BBR  2024 Summer Sessions Interview TrainingBBR  2024 Summer Sessions Interview Training
BBR 2024 Summer Sessions Interview Training
 
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdfবাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
 
How to Setup Warehouse & Location in Odoo 17 Inventory
How to Setup Warehouse & Location in Odoo 17 InventoryHow to Setup Warehouse & Location in Odoo 17 Inventory
How to Setup Warehouse & Location in Odoo 17 Inventory
 
BÀI TẬP BỔ TRỢ TIẾNG ANH LỚP 9 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2024-2025 - ...
BÀI TẬP BỔ TRỢ TIẾNG ANH LỚP 9 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2024-2025 - ...BÀI TẬP BỔ TRỢ TIẾNG ANH LỚP 9 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2024-2025 - ...
BÀI TẬP BỔ TRỢ TIẾNG ANH LỚP 9 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2024-2025 - ...
 
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
 
writing about opinions about Australia the movie
writing about opinions about Australia the moviewriting about opinions about Australia the movie
writing about opinions about Australia the movie
 
Walmart Business+ and Spark Good for Nonprofits.pdf
Walmart Business+ and Spark Good for Nonprofits.pdfWalmart Business+ and Spark Good for Nonprofits.pdf
Walmart Business+ and Spark Good for Nonprofits.pdf
 
Hindi varnamala | hindi alphabet PPT.pdf
Hindi varnamala | hindi alphabet PPT.pdfHindi varnamala | hindi alphabet PPT.pdf
Hindi varnamala | hindi alphabet PPT.pdf
 
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
 
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
 
Liberal Approach to the Study of Indian Politics.pdf
Liberal Approach to the Study of Indian Politics.pdfLiberal Approach to the Study of Indian Politics.pdf
Liberal Approach to the Study of Indian Politics.pdf
 
How to Create a More Engaging and Human Online Learning Experience
How to Create a More Engaging and Human Online Learning Experience How to Create a More Engaging and Human Online Learning Experience
How to Create a More Engaging and Human Online Learning Experience
 
Présentationvvvvvvvvvvvvvvvvvvvvvvvvvvvv2.pptx
Présentationvvvvvvvvvvvvvvvvvvvvvvvvvvvv2.pptxPrésentationvvvvvvvvvvvvvvvvvvvvvvvvvvvv2.pptx
Présentationvvvvvvvvvvvvvvvvvvvvvvvvvvvv2.pptx
 
Film vocab for eal 3 students: Australia the movie
Film vocab for eal 3 students: Australia the movieFilm vocab for eal 3 students: Australia the movie
Film vocab for eal 3 students: Australia the movie
 
The Diamonds of 2023-2024 in the IGRA collection
The Diamonds of 2023-2024 in the IGRA collectionThe Diamonds of 2023-2024 in the IGRA collection
The Diamonds of 2023-2024 in the IGRA collection
 
Wound healing PPT
Wound healing PPTWound healing PPT
Wound healing PPT
 
The basics of sentences session 6pptx.pptx
The basics of sentences session 6pptx.pptxThe basics of sentences session 6pptx.pptx
The basics of sentences session 6pptx.pptx
 
How to deliver Powerpoint Presentations.pptx
How to deliver Powerpoint  Presentations.pptxHow to deliver Powerpoint  Presentations.pptx
How to deliver Powerpoint Presentations.pptx
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
 
Digital Artefact 1 - Tiny Home Environmental Design
Digital Artefact 1 - Tiny Home Environmental DesignDigital Artefact 1 - Tiny Home Environmental Design
Digital Artefact 1 - Tiny Home Environmental Design
 

PHP-03-Functions.ppt

  • 1. PHP Functions / Modularity Dr. Charles Severance www.wa4e.com
  • 2. 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.
  • 3. To function or not to function... • Organize your code into “paragraphs” - capture a complete thought and “name it”. • Don’t repeat yourself - make it work once and then reuse it. • If something gets too long or complex, break up logical chunks and put those chunks in functions. • Make a library of common stuff that you do over and over - perhaps share this with your friends...
  • 6. Built-In Functions... • Much of the power of PHP comes from its built-in functions. • Many are modeled after C string library functions (i.e. strlen()). echo strrev(" .dlrow olleH"); echo str_repeat("Hip ", 2); echo strtoupper("hooray!"); echo strlen("intro"); echo "n"; Hello world. Hip Hip HOORAY! 5
  • 7. Defining Your Own Functions We use the function keyword to define a function, we name the function and take optional argument variables. The body of the function is in a block of code { } function greet() { print "Hellon"; } greet(); greet(); Hello Hello
  • 8. Choosing Function Names • Much like variable names - but do not start with a dollar sign • Start with a letter or underscore - consist of letters, numbers, and underscores ( _ ) • Avoid built-in function names • Case does not matter – but please do not take advantage of this
  • 9. 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"; } print greeting() . " Glennn"; print greeting() . " Sallyn"; Hello Glenn Hello Sally
  • 10. 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"; if ( $lang == 'fr' ) return "Bonjour"; return "Hello"; } print howdy('es') . " Glennn"; print howdy('fr') . " Sallyn"; Hola Glenn Bonjour Sally
  • 11. 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"; } print howdy() . " Glennn"; print howdy('fr') . " Sallyn"; Hola Glenn Bonjour Sally
  • 12. 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; return $alias; } $val = 10; $dval = double($val); echo "Value = $val Doubled = $dvaln"; Value = 10 Doubled = 20
  • 13. 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; } $val = 10; triple($val); echo "Triple = $valn"; Triple = 30
  • 16. Variable Scope • In general, variable names used inside of function code do not mix with the variables outside of the function to avoid unexpected side effects if two programmers use the same variable name in different parts of the code. • We call this “name spacing” the variables. The function variables are in one “name space” whilst the main variables are in another “name space”. http://php.net/manual/en/language.variables.scope.php
  • 17. Normal Scope (isolated) function tryzap() { $val = 100; } $val = 10; tryzap(); echo "TryZap = $valn"; TryZap = 10 http://php.net/manual/en/language.variables.superglobals.php Except for $_GET
  • 18. Global Scope (shared) function dozap() { global $val; $val = 100; } $val = 10; dozap(); echo "DoZap = $valn"; DoZap = 100 Use this wisely, young Jedi...
  • 19. Global Variables – Use Rarely • Passing variable in as parameter • Passing value back as return value • Passing variable in by reference • If you use global variables, use long names with nice unique prefixes global $LastOAuthBodyBaseString; global $LAST_OAUTH_BODY_BASE_STRING;
  • 20. Coping with Missing Bits Sometimes, depending on the version or configuration of a particular PHP instance, some functions may be missing. We can check that... if (function_exists("array_combine")){ echo "Function exists"; } else { echo "Function does not exist"; } This allows for evolution.
  • 22. One Heck of a Function… • PHP is a very configurable system and has lots of capabilities that can be plugged in. • The phpinfo() function prints out the internal configuration capabilities of your particular PHP installation, <?php phpinfo(); ?>
  • 23.
  • 24.
  • 25.
  • 27. Including Files in PHP • include "header.php"; - Pull the file in here • include_once "header.php"; - Pull the file in here unless it has already been pulled in before • require "header.php"; - Pull in the file here and die if it is missing • require_once "header.php"; - You can guess what this means... • These can look like functions - require_once("header.php");
  • 29. <?php require "top.php"; require "nav.php"; ?> <div id="container"> <h1>Web Applications...</h1> . . . </div> <?php require "foot.php"; index.php
  • 30. <?php require "top.php"; require "nav.php"; ?> <div id="container"> <iframeheight="4600" width="100%" frameborder="0" marginwidth="0"marginheight="0" scrolling="auto"src="software.php"> </iframe> </div> <?php require "foot.php"; install.php
  • 31. Summary • Built-in functions • Making new functions • Arguments - pass by value and pass by reference • Including and requiring files • Checking to see if functions are present
  • 32. Acknowledgements / Contributions These slides are Copyright 2010- Charles R. Severance (www.dr-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. Initial Development: Charles Severance, University of Michigan School of Information Insert new Contributors and Translators here including names and dates Continue new Contributors and Translators here

Editor's Notes

  1. Note from Chuck. Please retain and maintain this page as you remix and republish these materials. Please add any of your own improvements or contributions.