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();
?>
PHP-03-Functions.ppt
PHP-03-Functions.ppt
PHP-03-Functions.ppt
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 (20)

PHP FUNCTIONS AND ARRAY.pptx
PHP FUNCTIONS AND ARRAY.pptxPHP FUNCTIONS AND ARRAY.pptx
PHP FUNCTIONS AND ARRAY.pptx
ShaliniPrabakaran
 
Web Application Development using PHP Chapter 3
Web Application Development using PHP Chapter 3Web Application Development using PHP Chapter 3
Web Application Development using PHP Chapter 3
Mohd Harris Ahmad Jaal
 
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
 
Introduction in php part 2
Introduction in php part 2Introduction in php part 2
Introduction in php part 2
Bozhidar Boshnakov
 
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
 
function in php like control loop and its uses
function in php like control loop and its usesfunction in php like control loop and its uses
function in php like control loop and its uses
vishal choudhary
 
Php Reusing Code And Writing Functions
Php Reusing Code And Writing FunctionsPhp Reusing Code And Writing Functions
Php Reusing Code And Writing Functions
mussawir20
 
Php
PhpPhp
Php
Yoga Raja
 
Functuon
FunctuonFunctuon
Functuon
NithyaNithyav
 
Functuon
FunctuonFunctuon
Functuon
NithyaNithyav
 
function in php using like three type of function
function in php using  like three type of functionfunction in php using  like three type of function
function in php using like three type of function
vishal choudhary
 
Web Design EJ3
Web Design EJ3Web Design EJ3
Web Design EJ3
Aram Mohammed
 
PHP Unit 3 functions_in_php_2
PHP Unit 3 functions_in_php_2PHP Unit 3 functions_in_php_2
PHP Unit 3 functions_in_php_2
Kumar
 
Introduction to PHP_ Lexical structure_Array_Function_String
Introduction to PHP_ Lexical structure_Array_Function_StringIntroduction to PHP_ Lexical structure_Array_Function_String
Introduction to PHP_ Lexical structure_Array_Function_String
DeepakUlape2
 
John Rowley Notes
John Rowley NotesJohn Rowley Notes
John Rowley Notes
IBAT College
 
Functions in php
Functions in phpFunctions in php
Functions in php
Mudasir Syed
 
Php my sql - functions - arrays - tutorial - programmerblog.net
Php my sql - functions - arrays - tutorial - programmerblog.netPhp my sql - functions - arrays - tutorial - programmerblog.net
Php my sql - functions - arrays - tutorial - programmerblog.net
Programmer Blog
 
INTRODUCTION ON PHP - SERVER SIDE SCRIPTING LANGUAGE
INTRODUCTION ON PHP - SERVER SIDE SCRIPTING LANGUAGEINTRODUCTION ON PHP - SERVER SIDE SCRIPTING LANGUAGE
INTRODUCTION ON PHP - SERVER SIDE SCRIPTING LANGUAGE
PRIYADARSINIK3
 
Introduction to php
Introduction to phpIntroduction to php
Introduction to php
Taha Malampatti
 
PHP function
PHP functionPHP function
PHP function
monikadeshmane
 
PHP FUNCTIONS AND ARRAY.pptx
PHP FUNCTIONS AND ARRAY.pptxPHP FUNCTIONS AND ARRAY.pptx
PHP FUNCTIONS AND ARRAY.pptx
ShaliniPrabakaran
 
Web Application Development using PHP Chapter 3
Web Application Development using PHP Chapter 3Web Application Development using PHP Chapter 3
Web Application Development using PHP Chapter 3
Mohd Harris Ahmad Jaal
 
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
 
function in php like control loop and its uses
function in php like control loop and its usesfunction in php like control loop and its uses
function in php like control loop and its uses
vishal choudhary
 
Php Reusing Code And Writing Functions
Php Reusing Code And Writing FunctionsPhp Reusing Code And Writing Functions
Php Reusing Code And Writing Functions
mussawir20
 
function in php using like three type of function
function in php using  like three type of functionfunction in php using  like three type of function
function in php using like three type of function
vishal choudhary
 
PHP Unit 3 functions_in_php_2
PHP Unit 3 functions_in_php_2PHP Unit 3 functions_in_php_2
PHP Unit 3 functions_in_php_2
Kumar
 
Introduction to PHP_ Lexical structure_Array_Function_String
Introduction to PHP_ Lexical structure_Array_Function_StringIntroduction to PHP_ Lexical structure_Array_Function_String
Introduction to PHP_ Lexical structure_Array_Function_String
DeepakUlape2
 
Php my sql - functions - arrays - tutorial - programmerblog.net
Php my sql - functions - arrays - tutorial - programmerblog.netPhp my sql - functions - arrays - tutorial - programmerblog.net
Php my sql - functions - arrays - tutorial - programmerblog.net
Programmer Blog
 
INTRODUCTION ON PHP - SERVER SIDE SCRIPTING LANGUAGE
INTRODUCTION ON PHP - SERVER SIDE SCRIPTING LANGUAGEINTRODUCTION ON PHP - SERVER SIDE SCRIPTING LANGUAGE
INTRODUCTION ON PHP - SERVER SIDE SCRIPTING LANGUAGE
PRIYADARSINIK3
 

Recently uploaded (20)

Providing Better Biodiversity Through Better Data
Providing Better Biodiversity Through Better DataProviding Better Biodiversity Through Better Data
Providing Better Biodiversity Through Better Data
Safe Software
 
Integration Ignited Redefining Event-Driven Architecture at Wix - EventCentric
Integration Ignited Redefining Event-Driven Architecture at Wix - EventCentricIntegration Ignited Redefining Event-Driven Architecture at Wix - EventCentric
Integration Ignited Redefining Event-Driven Architecture at Wix - EventCentric
Natan Silnitsky
 
Build Smarter, Deliver Faster with Choreo - An AI Native Internal Developer P...
Build Smarter, Deliver Faster with Choreo - An AI Native Internal Developer P...Build Smarter, Deliver Faster with Choreo - An AI Native Internal Developer P...
Build Smarter, Deliver Faster with Choreo - An AI Native Internal Developer P...
WSO2
 
IMAGE CLASSIFICATION USING CONVOLUTIONAL NEURAL NETWORK.P.pptx
IMAGE CLASSIFICATION USING CONVOLUTIONAL NEURAL NETWORK.P.pptxIMAGE CLASSIFICATION USING CONVOLUTIONAL NEURAL NETWORK.P.pptx
IMAGE CLASSIFICATION USING CONVOLUTIONAL NEURAL NETWORK.P.pptx
usmanch7829
 
Marketo & Dynamics can be Most Excellent to Each Other – The Sequel
Marketo & Dynamics can be Most Excellent to Each Other – The SequelMarketo & Dynamics can be Most Excellent to Each Other – The Sequel
Marketo & Dynamics can be Most Excellent to Each Other – The Sequel
BradBedford3
 
DevOps for AI: running LLMs in production with Kubernetes and KubeFlow
DevOps for AI: running LLMs in production with Kubernetes and KubeFlowDevOps for AI: running LLMs in production with Kubernetes and KubeFlow
DevOps for AI: running LLMs in production with Kubernetes and KubeFlow
Aarno Aukia
 
Shell Skill Tree - LabEx Certification (LabEx)
Shell Skill Tree - LabEx Certification (LabEx)Shell Skill Tree - LabEx Certification (LabEx)
Shell Skill Tree - LabEx Certification (LabEx)
VICTOR MAESTRE RAMIREZ
 
Wondershare PDFelement Pro 11.4.20.3548 Crack Free Download
Wondershare PDFelement Pro 11.4.20.3548 Crack Free DownloadWondershare PDFelement Pro 11.4.20.3548 Crack Free Download
Wondershare PDFelement Pro 11.4.20.3548 Crack Free Download
Puppy jhon
 
Key AI Technologies Used by Indian Artificial Intelligence Companies
Key AI Technologies Used by Indian Artificial Intelligence CompaniesKey AI Technologies Used by Indian Artificial Intelligence Companies
Key AI Technologies Used by Indian Artificial Intelligence Companies
Mypcot Infotech
 
How Insurance Policy Administration Streamlines Policy Lifecycle for Agile Op...
How Insurance Policy Administration Streamlines Policy Lifecycle for Agile Op...How Insurance Policy Administration Streamlines Policy Lifecycle for Agile Op...
How Insurance Policy Administration Streamlines Policy Lifecycle for Agile Op...
Insurance Tech Services
 
Bonk coin airdrop_ Everything You Need to Know.pdf
Bonk coin airdrop_ Everything You Need to Know.pdfBonk coin airdrop_ Everything You Need to Know.pdf
Bonk coin airdrop_ Everything You Need to Know.pdf
Herond Labs
 
IBM Rational Unified Process For Software Engineering - Introduction
IBM Rational Unified Process For Software Engineering - IntroductionIBM Rational Unified Process For Software Engineering - Introduction
IBM Rational Unified Process For Software Engineering - Introduction
Gaurav Sharma
 
Software Engineering Process, Notation & Tools Introduction - Part 3
Software Engineering Process, Notation & Tools Introduction - Part 3Software Engineering Process, Notation & Tools Introduction - Part 3
Software Engineering Process, Notation & Tools Introduction - Part 3
Gaurav Sharma
 
Generative Artificial Intelligence and its Applications
Generative Artificial Intelligence and its ApplicationsGenerative Artificial Intelligence and its Applications
Generative Artificial Intelligence and its Applications
SandeepKS52
 
The Future of Open Source Reporting Best Alternatives to Jaspersoft.pdf
The Future of Open Source Reporting Best Alternatives to Jaspersoft.pdfThe Future of Open Source Reporting Best Alternatives to Jaspersoft.pdf
The Future of Open Source Reporting Best Alternatives to Jaspersoft.pdf
Varsha Nayak
 
How Insurance Policy Management Software Streamlines Operations
How Insurance Policy Management Software Streamlines OperationsHow Insurance Policy Management Software Streamlines Operations
How Insurance Policy Management Software Streamlines Operations
Insurance Tech Services
 
Top 11 Fleet Management Software Providers in 2025 (2).pdf
Top 11 Fleet Management Software Providers in 2025 (2).pdfTop 11 Fleet Management Software Providers in 2025 (2).pdf
Top 11 Fleet Management Software Providers in 2025 (2).pdf
Trackobit
 
FME for Climate Data: Turning Big Data into Actionable Insights
FME for Climate Data: Turning Big Data into Actionable InsightsFME for Climate Data: Turning Big Data into Actionable Insights
FME for Climate Data: Turning Big Data into Actionable Insights
Safe Software
 
Who will create the languages of the future?
Who will create the languages of the future?Who will create the languages of the future?
Who will create the languages of the future?
Jordi Cabot
 
Software Testing & it’s types (DevOps)
Software  Testing & it’s  types (DevOps)Software  Testing & it’s  types (DevOps)
Software Testing & it’s types (DevOps)
S Pranav (Deepu)
 
Providing Better Biodiversity Through Better Data
Providing Better Biodiversity Through Better DataProviding Better Biodiversity Through Better Data
Providing Better Biodiversity Through Better Data
Safe Software
 
Integration Ignited Redefining Event-Driven Architecture at Wix - EventCentric
Integration Ignited Redefining Event-Driven Architecture at Wix - EventCentricIntegration Ignited Redefining Event-Driven Architecture at Wix - EventCentric
Integration Ignited Redefining Event-Driven Architecture at Wix - EventCentric
Natan Silnitsky
 
Build Smarter, Deliver Faster with Choreo - An AI Native Internal Developer P...
Build Smarter, Deliver Faster with Choreo - An AI Native Internal Developer P...Build Smarter, Deliver Faster with Choreo - An AI Native Internal Developer P...
Build Smarter, Deliver Faster with Choreo - An AI Native Internal Developer P...
WSO2
 
IMAGE CLASSIFICATION USING CONVOLUTIONAL NEURAL NETWORK.P.pptx
IMAGE CLASSIFICATION USING CONVOLUTIONAL NEURAL NETWORK.P.pptxIMAGE CLASSIFICATION USING CONVOLUTIONAL NEURAL NETWORK.P.pptx
IMAGE CLASSIFICATION USING CONVOLUTIONAL NEURAL NETWORK.P.pptx
usmanch7829
 
Marketo & Dynamics can be Most Excellent to Each Other – The Sequel
Marketo & Dynamics can be Most Excellent to Each Other – The SequelMarketo & Dynamics can be Most Excellent to Each Other – The Sequel
Marketo & Dynamics can be Most Excellent to Each Other – The Sequel
BradBedford3
 
DevOps for AI: running LLMs in production with Kubernetes and KubeFlow
DevOps for AI: running LLMs in production with Kubernetes and KubeFlowDevOps for AI: running LLMs in production with Kubernetes and KubeFlow
DevOps for AI: running LLMs in production with Kubernetes and KubeFlow
Aarno Aukia
 
Shell Skill Tree - LabEx Certification (LabEx)
Shell Skill Tree - LabEx Certification (LabEx)Shell Skill Tree - LabEx Certification (LabEx)
Shell Skill Tree - LabEx Certification (LabEx)
VICTOR MAESTRE RAMIREZ
 
Wondershare PDFelement Pro 11.4.20.3548 Crack Free Download
Wondershare PDFelement Pro 11.4.20.3548 Crack Free DownloadWondershare PDFelement Pro 11.4.20.3548 Crack Free Download
Wondershare PDFelement Pro 11.4.20.3548 Crack Free Download
Puppy jhon
 
Key AI Technologies Used by Indian Artificial Intelligence Companies
Key AI Technologies Used by Indian Artificial Intelligence CompaniesKey AI Technologies Used by Indian Artificial Intelligence Companies
Key AI Technologies Used by Indian Artificial Intelligence Companies
Mypcot Infotech
 
How Insurance Policy Administration Streamlines Policy Lifecycle for Agile Op...
How Insurance Policy Administration Streamlines Policy Lifecycle for Agile Op...How Insurance Policy Administration Streamlines Policy Lifecycle for Agile Op...
How Insurance Policy Administration Streamlines Policy Lifecycle for Agile Op...
Insurance Tech Services
 
Bonk coin airdrop_ Everything You Need to Know.pdf
Bonk coin airdrop_ Everything You Need to Know.pdfBonk coin airdrop_ Everything You Need to Know.pdf
Bonk coin airdrop_ Everything You Need to Know.pdf
Herond Labs
 
IBM Rational Unified Process For Software Engineering - Introduction
IBM Rational Unified Process For Software Engineering - IntroductionIBM Rational Unified Process For Software Engineering - Introduction
IBM Rational Unified Process For Software Engineering - Introduction
Gaurav Sharma
 
Software Engineering Process, Notation & Tools Introduction - Part 3
Software Engineering Process, Notation & Tools Introduction - Part 3Software Engineering Process, Notation & Tools Introduction - Part 3
Software Engineering Process, Notation & Tools Introduction - Part 3
Gaurav Sharma
 
Generative Artificial Intelligence and its Applications
Generative Artificial Intelligence and its ApplicationsGenerative Artificial Intelligence and its Applications
Generative Artificial Intelligence and its Applications
SandeepKS52
 
The Future of Open Source Reporting Best Alternatives to Jaspersoft.pdf
The Future of Open Source Reporting Best Alternatives to Jaspersoft.pdfThe Future of Open Source Reporting Best Alternatives to Jaspersoft.pdf
The Future of Open Source Reporting Best Alternatives to Jaspersoft.pdf
Varsha Nayak
 
How Insurance Policy Management Software Streamlines Operations
How Insurance Policy Management Software Streamlines OperationsHow Insurance Policy Management Software Streamlines Operations
How Insurance Policy Management Software Streamlines Operations
Insurance Tech Services
 
Top 11 Fleet Management Software Providers in 2025 (2).pdf
Top 11 Fleet Management Software Providers in 2025 (2).pdfTop 11 Fleet Management Software Providers in 2025 (2).pdf
Top 11 Fleet Management Software Providers in 2025 (2).pdf
Trackobit
 
FME for Climate Data: Turning Big Data into Actionable Insights
FME for Climate Data: Turning Big Data into Actionable InsightsFME for Climate Data: Turning Big Data into Actionable Insights
FME for Climate Data: Turning Big Data into Actionable Insights
Safe Software
 
Who will create the languages of the future?
Who will create the languages of the future?Who will create the languages of the future?
Who will create the languages of the future?
Jordi Cabot
 
Software Testing & it’s types (DevOps)
Software  Testing & it’s  types (DevOps)Software  Testing & it’s  types (DevOps)
Software Testing & it’s types (DevOps)
S Pranav (Deepu)
 
Ad

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(); ?>
  • 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

  • #33: 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.