SlideShare a Scribd company logo
Reusing Code and Writing Functions All about functions, arguments, passing by reference, globals and scope
Introduction This part will discuss about php function, arguments, globals and scope, with an efficient way structuring php program. This part teaches you how to build them (once), use them (many times), pass them arguments and have them return values, and generally make your scripts more compact, efficient and maintainable.
Why function? There are three important reasons why functions are a good.  First: user-defined functions allow you to separate your code into easily identifiable subsections - which are easier to understand and debug.  Second: functions make your program modular, allowing you to write a piece of code once and then re-use it multiple times within the same program.  Third: functions simplify code updates or changes, because the change needs only to be implemented in a single place (the function definition). Functions thus save time, money and electrons.
Example of function <?php  // define a function  function  myStandardResponse () {      echo  &quot;Get lost, jerk!<br /><br />&quot; ;  }  // on the bus  echo  &quot;Hey lady, can you spare a dime? <br />&quot; ;  myStandardResponse ();  ?> ----Output---- Hey lady, can you spare a dime?  Get lost, jerk!  Function myStandardResponse created. Invoke the function, by calling myStandardResponse().
Typical format for a function  function function_name (optional function arguments) {      statement 1...      statement 2...      .      .      .      statement n...  }
Arguments A function without an arguments will print the same value each time it being invoke. Putting some arguments will get the functions to return a different value each time they are invoked. .  Arguments work by using a placeholder to represent a certain variable within a function. Values for this variable are provided to the function at run-time from the main program. Since the input to the function will differ at each invocation, so will the output.
Example of arguments Function with one arguments <?php  // define a function  function  getCircumference ( $radius ) {      echo  &quot;Circumference of a circle with radius $radius is &quot; . sprintf ( &quot;%4.2f&quot; , ( 2  *  $radius  *  pi ())). &quot;<br />&quot; ;  }  // call a function with an argument  getCircumference ( 10 );  // call the same function with another argument  getCircumference ( 20 );  ?>   --output-- Circumference of a circle with radius 10 is 62.83 Circumference of a circle with radius 20 is 125.66 getCircumference() function is called with an argument. The argument is assigned to the placeholder variable $radius within the function, and then acted upon by the code within the function definition.
Function with more than one arguments <?php  // define a function  function  changeCase ( $str ,  $flag ) {       /* check the flag variable and branch the code */       switch( $flag ) {          case  'U' :    // change to uppercase               print  strtoupper ( $str ). &quot;<br />&quot; ;              break;          case  'L' :    // change to lowercase               print  strtolower ( $str ). &quot;<br />&quot; ;              break;          default:              print  $str . &quot;<br />&quot; ;              break;      }  }  // call the function  changeCase ( &quot;The cow jumped over the moon&quot; ,  &quot;U&quot; );  changeCase ( &quot;Hello Sam&quot; ,  &quot;L&quot; );  ?>   --output— THE COW JUMPED OVER THE MOON hello sam
In the previous script, we also can pass more than one arguments to the function. Depending on the value of the second argument, program flow within the function moves to the appropriate branch and manipulates the first argument.
Return a value The functions on the previous page simply printed their output to the screen.  But what if you want the function to do something else with the result? In PHP, you can have a function return a value, such as the result of a calculation, to the statement that called it.  This is done using a  return  statement within the function.
Examples <?php  // define a function  function  getCircumference ( $radius ) {       // return value       return ( 2  *  $radius  *  pi ());  }  /* call a function with an argument and store the result in a variable */  $result  =  getCircumference ( 10 );  /* call the same function with another argument and print the return value */  print  getCircumference ( 20 );  ?>   --output— 125.663706144  The argument passed to the getCircumference() function is processed, and the result is returned to the main program, where it may be captured in a variable, printed, or dealt with in other ways.
Examples cont….. Use the result of a function inside another function  <?php  // define a function  function  getCircumference ( $radius ) {  // return value       return ( 2  *  $radius  *  pi ());  }  // print the return value after formatting it  print  &quot;The answer is &quot; . sprintf ( &quot;%4.2f&quot; ,  getCircumference ( 20 ));  ?>   --output— The answer is 125.66
Examples cont….. A function can just as easily return an array <?php  /* define a function that can accept a list of email addresses */  function  getUniqueDomains ( $list ) {       /* iterate over the list, split addresses and add domain part to another array */       $domains  = array();      foreach ( $list  as  $l ) {           $arr  =  explode ( &quot;@&quot; ,  $l );           $domains [] =  trim ( $arr [ 1 ]);      }       // remove duplicates and return       return  array_unique ( $domains );  }  // read email addresses from a file into an array  $fileContents  =  file ( &quot;data.txt&quot; );  /* pass the file contents to the function and retrieve the result array */  $returnArray  =  getUniqueDomains ( $fileContents );  // process the return array  foreach ( $returnArray  as  $d ) {      print  &quot;$d, &quot; ;  }  ?>   data.txt: [email_address] [email_address] [email_address] --output— yahoo.com, hotmail.com, cosmopoint.com,
Marching arguments order Order in which arguments are passed to a function can be important. It will affect the value that will pass to the variables in function.
Examples of argument order <?php  // define a function  function  introduce ( $name ,  $place ) {      print  &quot;Hello, I am $name from $place&quot; ;  }  // call function  introduce ( &quot;Moonface&quot; ,  &quot;The Faraway Tree&quot; );  ?>   The first value ‘Moonface’ will assign to the $name, while the “The Faraway Tree” will assign to the $place.
Examples cont….. The output:  introduce ( &quot;Moonface&quot; ,  &quot;The Faraway Tree&quot; ); Hello, I am Moonface from The Faraway Tree  If you reversed the order in which arguments were passed to the function introduce ( &quot;The Faraway Tree Moonface&quot; ,  &quot;Moonface&quot; ); Hello, I am The Faraway Tree from Moonface  If forgot to pass a required argument altogether  Warning: Missing argument 2 for introduce() in xx.php on line 3 Hello, I am Moonface from
Default value for arguments In order to avoid such errors, PHP allows the user to specify default values for all the arguments in a user-defined function. These default values are used if the function invocation is missing some arguments.
Examples <?php  // define a function  function  introduce ( $name = &quot;John Doe&quot; ,  $place = &quot;London&quot; ) {      print  &quot;Hello, I am $name from $place&quot; ;  }  // call function  introduce ( &quot;Moonface&quot; );  ?> ---Output Hello, I am Moonface from London The function has been called with only a single argument, even though the function definition requires two. New value will overwrite the default value, while the missing arguments will used the default value.
Function functions  All the examples on the previous page have one thing in common: the number of arguments in the function definition is fixed.  PHP 4.x also supports variable-length argument lists, by using the  func_num_args()  and  func_get_args()  commands.  These functions are called &quot;function functions&quot;.
Example <?php  // define a function  function  someFunc () {       // get the number of arguments passed       $numArgs  =  func_num_args ();      // get the arguments       $args  =  func_get_args ();       // print the arguments       print  &quot;You sent me the following arguments: &quot; ;      for ( $x  =  0 ;  $x  <  $numArgs ;  $x ++) {          print  &quot;<br />Argument $x: &quot; ;           /* check if an array was passed and, if so, iterate and print contents */           if ( is_array ( $args [ $x ])) {              print  &quot; ARRAY &quot; ;              foreach ( $args [ $x ] as  $index  =>  $element ) {                  print  &quot; $index => $element &quot; ;              }          }          else {              print  &quot; $args[$x] &quot; ;          }      }  }  // call a function with different arguments  someFunc ( &quot;red&quot; ,  &quot;green&quot; ,  &quot;blue&quot; , array( 4 , 5 ),  &quot;yellow&quot; );  ?>   --output-- You sent me the following arguments:  Argument 0: red  Argument 1: green  Argument 2: blue  Argument 3: ARRAY 0 => 4 1 => 5  Argument 4: yellow
Globals The  global  command allows the variable to be used outside the function after the function being invoked. To have variables within a function accessible from outside it (and vice-versa), declare the variables as &quot; global &quot;
Example Without  global  command <?php   // define a variable in the main program  $today  =  &quot;Tuesday&quot; ;  // define a function  function  getDay () {       // define a variable inside the function       $today  =  &quot;Saturday&quot; ;       // print the variable       print  &quot;It is $today inside the function<br />&quot; ;  }  // call the function  getDay ();  // print the variable  print  &quot;It is $today outside the function&quot; ;  ?>   --output— It is Saturday inside the function It is Tuesday outside the function
Example cont… With a  global  command <?php  // define a variable in the main program  $today  =  &quot;Tuesday&quot; ;  // define a function  function  getDay () {       // make the variable global       global  $today ;             // define a variable inside the function       $today  =  &quot;Saturday&quot; ;       // print the variable       print  &quot;It is $today inside the function<br />&quot; ;  }  // print the variable  print  &quot;It is $today before running the function<br />&quot; ;  // call the function  getDay ();  // print the variable  print  &quot;It is $today after running the function&quot; ;  ?>   ----output--- It is Tuesday before running the function It is Saturday inside the function It is Saturday after running the function
Passing by value and reference There are two method in passing the arguments either by value or by reference. Passing arguments to a function &quot;by value&quot; - meaning that a copy of the variable was passed to the function, while the original variable remained untouched. PHP also allows method to pass &quot;by reference&quot; - meaning that instead of passing a value to a function, it pass a reference (pointer) to the original variable, and have the function act on that instead of a copy.
Passing by value Example 1 <?php  // create a variable  $today  =  &quot;Saturday&quot; ;  // function to print the value of the variable  function  setDay ( $day ) {       $day  =  &quot;Tuesday&quot; ;      print  &quot;It is $day inside the function<br />&quot; ;  }  // call function  setDay ( $today );  // print the value of the variable  print  &quot;It is $today outside the function&quot; ;  ?>   --output— It is Tuesday inside the function It is Saturday inside the function
Passing by reference Example 2 <?php  // create a variable  $today  =  &quot;Saturday&quot; ;  // function to print the value of the variable  function  setDay (& $day ) {       $day  =  &quot;Tuesday&quot; ;      print  &quot;It is $day inside the function<br />&quot; ;  }  // call function  setDay ( $today );  // print the value of the variable  print  &quot;It is $today outside the function&quot; ;  ?>   --output— It is Tuesday inside the function It is Tuesday outside the function
Example 1 : The getDay() function is invoked, it passes the value &quot;Saturday&quot; to the function (&quot;passing by value&quot;). The original variable remains untouched; only its content is sent to the function. The function then acts on the content, modifying and displaying it. Example 2: Notice the ampersand (&) before the argument in the function definition. This tells PHP to use the variable reference instead of the variable value. When such a reference is passed to a function, the code inside the function acts on the reference, and modifies the content of the original variable (which the reference is pointing to) rather than a copy.
The discussion about variables would be incomplete without mentioning the two ways of passing variables. This, of course, is what the global keyword does inside a function: use a reference to ensure that changes to the variable inside the function also reflect outside it.  The PHP manual puts it best when it says &quot;...when you declare a variable as global $var you are in fact creating a reference to a global variable.
Ad

More Related Content

What's hot (20)

C.S. project report on railway ticket reservation
C.S. project report on railway ticket reservationC.S. project report on railway ticket reservation
C.S. project report on railway ticket reservation
Virat Prasad
 
Network بە زمانی کوردیی
Network بە زمانی کوردیی Network بە زمانی کوردیی
Network بە زمانی کوردیی
Rebin Daho
 
RF Optimization Slide deck.pptx
RF Optimization Slide deck.pptxRF Optimization Slide deck.pptx
RF Optimization Slide deck.pptx
ssuser2b76bb
 
3 g drive-test
3 g drive-test3 g drive-test
3 g drive-test
Aniekhan
 
Beginners PHP Tutorial
Beginners PHP TutorialBeginners PHP Tutorial
Beginners PHP Tutorial
alexjones89
 
Network(pr)kurdish
Network(pr)kurdishNetwork(pr)kurdish
Network(pr)kurdish
Aram Mohammed
 
Apuntes: Manejar el DOM con JavaScript
Apuntes: Manejar el DOM con JavaScriptApuntes: Manejar el DOM con JavaScript
Apuntes: Manejar el DOM con JavaScript
Francisco Javier Arce Anguiano
 
Jdbc ppt
Jdbc pptJdbc ppt
Jdbc ppt
sandeep54552
 
Php mysql
Php mysqlPhp mysql
Php mysql
Shehrevar Davierwala
 
NEI_LTE1235_ready_02.pdf
NEI_LTE1235_ready_02.pdfNEI_LTE1235_ready_02.pdf
NEI_LTE1235_ready_02.pdf
PLAGBEKomlanDaniel
 
LTC4263 - PSE Controller with Internal Switch
LTC4263 - PSE Controller with Internal SwitchLTC4263 - PSE Controller with Internal Switch
LTC4263 - PSE Controller with Internal Switch
Premier Farnell
 
Lezione 5: Socket SSL/ TLS
Lezione 5: Socket SSL/ TLSLezione 5: Socket SSL/ TLS
Lezione 5: Socket SSL/ TLS
Andrea Della Corte
 
UMTS/WCDMA Call Flows for CS services
UMTS/WCDMA Call Flows for CS servicesUMTS/WCDMA Call Flows for CS services
UMTS/WCDMA Call Flows for CS services
Justin MA (馬嘉昌)
 
Routing
RoutingRouting
Routing
Amna Nawazish
 
287995345-Huawei-WCDMA-Radio-Parameters-Optimization-Cases.pdf
287995345-Huawei-WCDMA-Radio-Parameters-Optimization-Cases.pdf287995345-Huawei-WCDMA-Radio-Parameters-Optimization-Cases.pdf
287995345-Huawei-WCDMA-Radio-Parameters-Optimization-Cases.pdf
ObeidAllah
 
VoLTE KPI Performance Explained
VoLTE KPI Performance ExplainedVoLTE KPI Performance Explained
VoLTE KPI Performance Explained
Vikas Shokeen
 
Ip, subnet, gateway and routers
Ip, subnet, gateway and routersIp, subnet, gateway and routers
Ip, subnet, gateway and routers
Adrian Suarez
 
OPEN SHORTEST PATH FIRST (OSPF)
OPEN SHORTEST PATH FIRST (OSPF)OPEN SHORTEST PATH FIRST (OSPF)
OPEN SHORTEST PATH FIRST (OSPF)
Ann Joseph
 
Neighbor guideline v1.0 rev
Neighbor guideline v1.0 revNeighbor guideline v1.0 rev
Neighbor guideline v1.0 rev
Nurul Ihsands
 
LTE network: How it all comes together architecture technical poster
LTE network: How it all comes together architecture technical posterLTE network: How it all comes together architecture technical poster
LTE network: How it all comes together architecture technical poster
David Swift
 
C.S. project report on railway ticket reservation
C.S. project report on railway ticket reservationC.S. project report on railway ticket reservation
C.S. project report on railway ticket reservation
Virat Prasad
 
Network بە زمانی کوردیی
Network بە زمانی کوردیی Network بە زمانی کوردیی
Network بە زمانی کوردیی
Rebin Daho
 
RF Optimization Slide deck.pptx
RF Optimization Slide deck.pptxRF Optimization Slide deck.pptx
RF Optimization Slide deck.pptx
ssuser2b76bb
 
3 g drive-test
3 g drive-test3 g drive-test
3 g drive-test
Aniekhan
 
Beginners PHP Tutorial
Beginners PHP TutorialBeginners PHP Tutorial
Beginners PHP Tutorial
alexjones89
 
Network(pr)kurdish
Network(pr)kurdishNetwork(pr)kurdish
Network(pr)kurdish
Aram Mohammed
 
NEI_LTE1235_ready_02.pdf
NEI_LTE1235_ready_02.pdfNEI_LTE1235_ready_02.pdf
NEI_LTE1235_ready_02.pdf
PLAGBEKomlanDaniel
 
LTC4263 - PSE Controller with Internal Switch
LTC4263 - PSE Controller with Internal SwitchLTC4263 - PSE Controller with Internal Switch
LTC4263 - PSE Controller with Internal Switch
Premier Farnell
 
Lezione 5: Socket SSL/ TLS
Lezione 5: Socket SSL/ TLSLezione 5: Socket SSL/ TLS
Lezione 5: Socket SSL/ TLS
Andrea Della Corte
 
287995345-Huawei-WCDMA-Radio-Parameters-Optimization-Cases.pdf
287995345-Huawei-WCDMA-Radio-Parameters-Optimization-Cases.pdf287995345-Huawei-WCDMA-Radio-Parameters-Optimization-Cases.pdf
287995345-Huawei-WCDMA-Radio-Parameters-Optimization-Cases.pdf
ObeidAllah
 
VoLTE KPI Performance Explained
VoLTE KPI Performance ExplainedVoLTE KPI Performance Explained
VoLTE KPI Performance Explained
Vikas Shokeen
 
Ip, subnet, gateway and routers
Ip, subnet, gateway and routersIp, subnet, gateway and routers
Ip, subnet, gateway and routers
Adrian Suarez
 
OPEN SHORTEST PATH FIRST (OSPF)
OPEN SHORTEST PATH FIRST (OSPF)OPEN SHORTEST PATH FIRST (OSPF)
OPEN SHORTEST PATH FIRST (OSPF)
Ann Joseph
 
Neighbor guideline v1.0 rev
Neighbor guideline v1.0 revNeighbor guideline v1.0 rev
Neighbor guideline v1.0 rev
Nurul Ihsands
 
LTE network: How it all comes together architecture technical poster
LTE network: How it all comes together architecture technical posterLTE network: How it all comes together architecture technical poster
LTE network: How it all comes together architecture technical poster
David Swift
 

Viewers also liked (7)

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
 
Functions in php
Functions in phpFunctions in php
Functions in php
Mudasir Syed
 
The many facets of code reuse in JavaScript
The many facets of code reuse in JavaScriptThe many facets of code reuse in JavaScript
The many facets of code reuse in JavaScript
Leonardo Borges
 
Writing Function Rules
Writing Function RulesWriting Function Rules
Writing Function Rules
Bitsy Griffin
 
The Role and Importance of Writing in our Society
The Role and Importance of Writing in our SocietyThe Role and Importance of Writing in our Society
The Role and Importance of Writing in our Society
ashleep123
 
SEO Master - Tuyet chieu dua website len trang 1 Google
SEO Master - Tuyet chieu dua website len trang 1 GoogleSEO Master - Tuyet chieu dua website len trang 1 Google
SEO Master - Tuyet chieu dua website len trang 1 Google
Nguyễn Trọng Thơ
 
8.4 Rules For Linear Functions
8.4 Rules For Linear Functions8.4 Rules For Linear Functions
8.4 Rules For Linear Functions
Jessca Lundin
 
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
 
Functions in php
Functions in phpFunctions in php
Functions in php
Mudasir Syed
 
The many facets of code reuse in JavaScript
The many facets of code reuse in JavaScriptThe many facets of code reuse in JavaScript
The many facets of code reuse in JavaScript
Leonardo Borges
 
Writing Function Rules
Writing Function RulesWriting Function Rules
Writing Function Rules
Bitsy Griffin
 
The Role and Importance of Writing in our Society
The Role and Importance of Writing in our SocietyThe Role and Importance of Writing in our Society
The Role and Importance of Writing in our Society
ashleep123
 
SEO Master - Tuyet chieu dua website len trang 1 Google
SEO Master - Tuyet chieu dua website len trang 1 GoogleSEO Master - Tuyet chieu dua website len trang 1 Google
SEO Master - Tuyet chieu dua website len trang 1 Google
Nguyễn Trọng Thơ
 
8.4 Rules For Linear Functions
8.4 Rules For Linear Functions8.4 Rules For Linear Functions
8.4 Rules For Linear Functions
Jessca Lundin
 
Ad

Similar to Php Reusing Code And Writing Functions (20)

LicĂŁo 13 functions
LicĂŁo 13 functionsLicĂŁo 13 functions
LicĂŁo 13 functions
AcĂĄcio Oliveira
 
Gift-VT Tools Development Overview
Gift-VT Tools Development OverviewGift-VT Tools Development Overview
Gift-VT Tools Development Overview
stn_tkiller
 
course slides -- powerpoint
course slides -- powerpointcourse slides -- powerpoint
course slides -- powerpoint
webhostingguy
 
PHP 5.3 Part 2 - Lambda Functions & Closures
PHP 5.3 Part 2 - Lambda Functions & ClosuresPHP 5.3 Part 2 - Lambda Functions & Closures
PHP 5.3 Part 2 - Lambda Functions & Closures
melechi
 
Classes function overloading
Classes function overloadingClasses function overloading
Classes function overloading
ankush_kumar
 
Go OO! - Real-life Design Patterns in PHP 5
Go OO! - Real-life Design Patterns in PHP 5Go OO! - Real-life Design Patterns in PHP 5
Go OO! - Real-life Design Patterns in PHP 5
Stephan Schmidt
 
02 Php Vars Op Control Etc
02 Php Vars Op Control Etc02 Php Vars Op Control Etc
02 Php Vars Op Control Etc
Geshan Manandhar
 
Introducing PHP Latest Updates
Introducing PHP Latest UpdatesIntroducing PHP Latest Updates
Introducing PHP Latest Updates
Iftekhar Eather
 
php user defined functions
php user defined functionsphp user defined functions
php user defined functions
vishnupriyapm4
 
Functions in C.pptx
Functions in C.pptxFunctions in C.pptx
Functions in C.pptx
KarthikSivagnanam2
 
Php
PhpPhp
Php
Rajkiran Mummadi
 
Php Learning show
Php Learning showPhp Learning show
Php Learning show
Gnugroup India
 
C++ Function
C++ FunctionC++ Function
C++ Function
Hajar
 
PHP7 - Scalar Type Hints & Return Types
PHP7 - Scalar Type Hints & Return TypesPHP7 - Scalar Type Hints & Return Types
PHP7 - Scalar Type Hints & Return Types
Eric Poe
 
PHP 5.3
PHP 5.3PHP 5.3
PHP 5.3
Chris Stone
 
JavaScript and UI Architecture Best Practices
JavaScript and UI Architecture Best PracticesJavaScript and UI Architecture Best Practices
JavaScript and UI Architecture Best Practices
Siarhei Barysiuk
 
Internet Technology and its Applications
Internet Technology and its ApplicationsInternet Technology and its Applications
Internet Technology and its Applications
amichoksi
 
PHP Workshop Notes
PHP Workshop NotesPHP Workshop Notes
PHP Workshop Notes
Pamela Fox
 
C Programming Language Part 7
C Programming Language Part 7C Programming Language Part 7
C Programming Language Part 7
Rumman Ansari
 
Kicking off with Zend Expressive and Doctrine ORM (PHP UK 2017)
Kicking off with Zend Expressive and Doctrine ORM (PHP UK 2017)Kicking off with Zend Expressive and Doctrine ORM (PHP UK 2017)
Kicking off with Zend Expressive and Doctrine ORM (PHP UK 2017)
James Titcumb
 
Gift-VT Tools Development Overview
Gift-VT Tools Development OverviewGift-VT Tools Development Overview
Gift-VT Tools Development Overview
stn_tkiller
 
course slides -- powerpoint
course slides -- powerpointcourse slides -- powerpoint
course slides -- powerpoint
webhostingguy
 
PHP 5.3 Part 2 - Lambda Functions & Closures
PHP 5.3 Part 2 - Lambda Functions & ClosuresPHP 5.3 Part 2 - Lambda Functions & Closures
PHP 5.3 Part 2 - Lambda Functions & Closures
melechi
 
Classes function overloading
Classes function overloadingClasses function overloading
Classes function overloading
ankush_kumar
 
Go OO! - Real-life Design Patterns in PHP 5
Go OO! - Real-life Design Patterns in PHP 5Go OO! - Real-life Design Patterns in PHP 5
Go OO! - Real-life Design Patterns in PHP 5
Stephan Schmidt
 
02 Php Vars Op Control Etc
02 Php Vars Op Control Etc02 Php Vars Op Control Etc
02 Php Vars Op Control Etc
Geshan Manandhar
 
Introducing PHP Latest Updates
Introducing PHP Latest UpdatesIntroducing PHP Latest Updates
Introducing PHP Latest Updates
Iftekhar Eather
 
php user defined functions
php user defined functionsphp user defined functions
php user defined functions
vishnupriyapm4
 
Php Learning show
Php Learning showPhp Learning show
Php Learning show
Gnugroup India
 
C++ Function
C++ FunctionC++ Function
C++ Function
Hajar
 
PHP7 - Scalar Type Hints & Return Types
PHP7 - Scalar Type Hints & Return TypesPHP7 - Scalar Type Hints & Return Types
PHP7 - Scalar Type Hints & Return Types
Eric Poe
 
JavaScript and UI Architecture Best Practices
JavaScript and UI Architecture Best PracticesJavaScript and UI Architecture Best Practices
JavaScript and UI Architecture Best Practices
Siarhei Barysiuk
 
Internet Technology and its Applications
Internet Technology and its ApplicationsInternet Technology and its Applications
Internet Technology and its Applications
amichoksi
 
PHP Workshop Notes
PHP Workshop NotesPHP Workshop Notes
PHP Workshop Notes
Pamela Fox
 
C Programming Language Part 7
C Programming Language Part 7C Programming Language Part 7
C Programming Language Part 7
Rumman Ansari
 
Kicking off with Zend Expressive and Doctrine ORM (PHP UK 2017)
Kicking off with Zend Expressive and Doctrine ORM (PHP UK 2017)Kicking off with Zend Expressive and Doctrine ORM (PHP UK 2017)
Kicking off with Zend Expressive and Doctrine ORM (PHP UK 2017)
James Titcumb
 
Ad

More from mussawir20 (20)

Php Operators N Controllers
Php Operators N ControllersPhp Operators N Controllers
Php Operators N Controllers
mussawir20
 
Php Calling Operators
Php Calling OperatorsPhp Calling Operators
Php Calling Operators
mussawir20
 
Database Design Process
Database Design ProcessDatabase Design Process
Database Design Process
mussawir20
 
Php Simple Xml
Php Simple XmlPhp Simple Xml
Php Simple Xml
mussawir20
 
Php String And Regular Expressions
Php String  And Regular ExpressionsPhp String  And Regular Expressions
Php String And Regular Expressions
mussawir20
 
Php Sq Lite
Php Sq LitePhp Sq Lite
Php Sq Lite
mussawir20
 
Php Sessoins N Cookies
Php Sessoins N CookiesPhp Sessoins N Cookies
Php Sessoins N Cookies
mussawir20
 
Php Rss
Php RssPhp Rss
Php Rss
mussawir20
 
Php Oop
Php OopPhp Oop
Php Oop
mussawir20
 
Php My Sql
Php My SqlPhp My Sql
Php My Sql
mussawir20
 
Php File Operations
Php File OperationsPhp File Operations
Php File Operations
mussawir20
 
Php Error Handling
Php Error HandlingPhp Error Handling
Php Error Handling
mussawir20
 
Php Crash Course
Php Crash CoursePhp Crash Course
Php Crash Course
mussawir20
 
Php Basic Security
Php Basic SecurityPhp Basic Security
Php Basic Security
mussawir20
 
Php Using Arrays
Php Using ArraysPhp Using Arrays
Php Using Arrays
mussawir20
 
Javascript Oop
Javascript OopJavascript Oop
Javascript Oop
mussawir20
 
Html
HtmlHtml
Html
mussawir20
 
Javascript
JavascriptJavascript
Javascript
mussawir20
 
Object Range
Object RangeObject Range
Object Range
mussawir20
 
Prototype Utility Methods(1)
Prototype Utility Methods(1)Prototype Utility Methods(1)
Prototype Utility Methods(1)
mussawir20
 
Php Operators N Controllers
Php Operators N ControllersPhp Operators N Controllers
Php Operators N Controllers
mussawir20
 
Php Calling Operators
Php Calling OperatorsPhp Calling Operators
Php Calling Operators
mussawir20
 
Database Design Process
Database Design ProcessDatabase Design Process
Database Design Process
mussawir20
 
Php Simple Xml
Php Simple XmlPhp Simple Xml
Php Simple Xml
mussawir20
 
Php String And Regular Expressions
Php String  And Regular ExpressionsPhp String  And Regular Expressions
Php String And Regular Expressions
mussawir20
 
Php Sq Lite
Php Sq LitePhp Sq Lite
Php Sq Lite
mussawir20
 
Php Sessoins N Cookies
Php Sessoins N CookiesPhp Sessoins N Cookies
Php Sessoins N Cookies
mussawir20
 
Php My Sql
Php My SqlPhp My Sql
Php My Sql
mussawir20
 
Php File Operations
Php File OperationsPhp File Operations
Php File Operations
mussawir20
 
Php Error Handling
Php Error HandlingPhp Error Handling
Php Error Handling
mussawir20
 
Php Crash Course
Php Crash CoursePhp Crash Course
Php Crash Course
mussawir20
 
Php Basic Security
Php Basic SecurityPhp Basic Security
Php Basic Security
mussawir20
 
Php Using Arrays
Php Using ArraysPhp Using Arrays
Php Using Arrays
mussawir20
 
Javascript Oop
Javascript OopJavascript Oop
Javascript Oop
mussawir20
 
Javascript
JavascriptJavascript
Javascript
mussawir20
 
Object Range
Object RangeObject Range
Object Range
mussawir20
 
Prototype Utility Methods(1)
Prototype Utility Methods(1)Prototype Utility Methods(1)
Prototype Utility Methods(1)
mussawir20
 

Recently uploaded (20)

Technology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data AnalyticsTechnology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data Analytics
InData Labs
 
2025-05-Q4-2024-Investor-Presentation.pptx
2025-05-Q4-2024-Investor-Presentation.pptx2025-05-Q4-2024-Investor-Presentation.pptx
2025-05-Q4-2024-Investor-Presentation.pptx
Samuele Fogagnolo
 
Rusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond SparkRusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond Spark
carlyakerly1
 
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Impelsys Inc.
 
Mobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi ArabiaMobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi Arabia
Steve Jonas
 
Linux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdfLinux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdf
RHCSA Guru
 
Big Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur MorganBig Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur Morgan
Arthur Morgan
 
Cybersecurity Identity and Access Solutions using Azure AD
Cybersecurity Identity and Access Solutions using Azure ADCybersecurity Identity and Access Solutions using Azure AD
Cybersecurity Identity and Access Solutions using Azure AD
VICTOR MAESTRE RAMIREZ
 
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
BookNet Canada
 
Procurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptxProcurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptx
Jon Hansen
 
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
BookNet Canada
 
Generative Artificial Intelligence (GenAI) in Business
Generative Artificial Intelligence (GenAI) in BusinessGenerative Artificial Intelligence (GenAI) in Business
Generative Artificial Intelligence (GenAI) in Business
Dr. Tathagat Varma
 
Heap, Types of Heap, Insertion and Deletion
Heap, Types of Heap, Insertion and DeletionHeap, Types of Heap, Insertion and Deletion
Heap, Types of Heap, Insertion and Deletion
Jaydeep Kale
 
How analogue intelligence complements AI
How analogue intelligence complements AIHow analogue intelligence complements AI
How analogue intelligence complements AI
Paul Rowe
 
Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)
Ortus Solutions, Corp
 
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptxDevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
Justin Reock
 
Semantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AISemantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AI
artmondano
 
AI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global TrendsAI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global Trends
InData Labs
 
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-UmgebungenHCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
panagenda
 
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded DevelopersLinux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Toradex
 
Technology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data AnalyticsTechnology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data Analytics
InData Labs
 
2025-05-Q4-2024-Investor-Presentation.pptx
2025-05-Q4-2024-Investor-Presentation.pptx2025-05-Q4-2024-Investor-Presentation.pptx
2025-05-Q4-2024-Investor-Presentation.pptx
Samuele Fogagnolo
 
Rusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond SparkRusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond Spark
carlyakerly1
 
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Impelsys Inc.
 
Mobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi ArabiaMobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi Arabia
Steve Jonas
 
Linux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdfLinux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdf
RHCSA Guru
 
Big Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur MorganBig Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur Morgan
Arthur Morgan
 
Cybersecurity Identity and Access Solutions using Azure AD
Cybersecurity Identity and Access Solutions using Azure ADCybersecurity Identity and Access Solutions using Azure AD
Cybersecurity Identity and Access Solutions using Azure AD
VICTOR MAESTRE RAMIREZ
 
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
BookNet Canada
 
Procurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptxProcurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptx
Jon Hansen
 
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
BookNet Canada
 
Generative Artificial Intelligence (GenAI) in Business
Generative Artificial Intelligence (GenAI) in BusinessGenerative Artificial Intelligence (GenAI) in Business
Generative Artificial Intelligence (GenAI) in Business
Dr. Tathagat Varma
 
Heap, Types of Heap, Insertion and Deletion
Heap, Types of Heap, Insertion and DeletionHeap, Types of Heap, Insertion and Deletion
Heap, Types of Heap, Insertion and Deletion
Jaydeep Kale
 
How analogue intelligence complements AI
How analogue intelligence complements AIHow analogue intelligence complements AI
How analogue intelligence complements AI
Paul Rowe
 
Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)
Ortus Solutions, Corp
 
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptxDevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
Justin Reock
 
Semantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AISemantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AI
artmondano
 
AI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global TrendsAI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global Trends
InData Labs
 
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-UmgebungenHCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
panagenda
 
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded DevelopersLinux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Toradex
 

Php Reusing Code And Writing Functions

  • 1. Reusing Code and Writing Functions All about functions, arguments, passing by reference, globals and scope
  • 2. Introduction This part will discuss about php function, arguments, globals and scope, with an efficient way structuring php program. This part teaches you how to build them (once), use them (many times), pass them arguments and have them return values, and generally make your scripts more compact, efficient and maintainable.
  • 3. Why function? There are three important reasons why functions are a good. First: user-defined functions allow you to separate your code into easily identifiable subsections - which are easier to understand and debug. Second: functions make your program modular, allowing you to write a piece of code once and then re-use it multiple times within the same program. Third: functions simplify code updates or changes, because the change needs only to be implemented in a single place (the function definition). Functions thus save time, money and electrons.
  • 4. Example of function <?php // define a function function myStandardResponse () {     echo &quot;Get lost, jerk!<br /><br />&quot; ; } // on the bus echo &quot;Hey lady, can you spare a dime? <br />&quot; ; myStandardResponse (); ?> ----Output---- Hey lady, can you spare a dime? Get lost, jerk! Function myStandardResponse created. Invoke the function, by calling myStandardResponse().
  • 5. Typical format for a function function function_name (optional function arguments) {     statement 1...     statement 2...     .     .     .     statement n... }
  • 6. Arguments A function without an arguments will print the same value each time it being invoke. Putting some arguments will get the functions to return a different value each time they are invoked. . Arguments work by using a placeholder to represent a certain variable within a function. Values for this variable are provided to the function at run-time from the main program. Since the input to the function will differ at each invocation, so will the output.
  • 7. Example of arguments Function with one arguments <?php // define a function function getCircumference ( $radius ) {     echo &quot;Circumference of a circle with radius $radius is &quot; . sprintf ( &quot;%4.2f&quot; , ( 2 * $radius * pi ())). &quot;<br />&quot; ; } // call a function with an argument getCircumference ( 10 ); // call the same function with another argument getCircumference ( 20 ); ?> --output-- Circumference of a circle with radius 10 is 62.83 Circumference of a circle with radius 20 is 125.66 getCircumference() function is called with an argument. The argument is assigned to the placeholder variable $radius within the function, and then acted upon by the code within the function definition.
  • 8. Function with more than one arguments <?php // define a function function changeCase ( $str , $flag ) {      /* check the flag variable and branch the code */      switch( $flag ) {         case 'U' : // change to uppercase              print strtoupper ( $str ). &quot;<br />&quot; ;             break;         case 'L' : // change to lowercase              print strtolower ( $str ). &quot;<br />&quot; ;             break;         default:             print $str . &quot;<br />&quot; ;             break;     } } // call the function changeCase ( &quot;The cow jumped over the moon&quot; , &quot;U&quot; ); changeCase ( &quot;Hello Sam&quot; , &quot;L&quot; ); ?> --output— THE COW JUMPED OVER THE MOON hello sam
  • 9. In the previous script, we also can pass more than one arguments to the function. Depending on the value of the second argument, program flow within the function moves to the appropriate branch and manipulates the first argument.
  • 10. Return a value The functions on the previous page simply printed their output to the screen. But what if you want the function to do something else with the result? In PHP, you can have a function return a value, such as the result of a calculation, to the statement that called it. This is done using a return statement within the function.
  • 11. Examples <?php // define a function function getCircumference ( $radius ) {      // return value      return ( 2 * $radius * pi ()); } /* call a function with an argument and store the result in a variable */ $result = getCircumference ( 10 ); /* call the same function with another argument and print the return value */ print getCircumference ( 20 ); ?> --output— 125.663706144 The argument passed to the getCircumference() function is processed, and the result is returned to the main program, where it may be captured in a variable, printed, or dealt with in other ways.
  • 12. Examples cont….. Use the result of a function inside another function <?php // define a function function getCircumference ( $radius ) { // return value      return ( 2 * $radius * pi ()); } // print the return value after formatting it print &quot;The answer is &quot; . sprintf ( &quot;%4.2f&quot; , getCircumference ( 20 )); ?> --output— The answer is 125.66
  • 13. Examples cont….. A function can just as easily return an array <?php /* define a function that can accept a list of email addresses */ function getUniqueDomains ( $list ) {      /* iterate over the list, split addresses and add domain part to another array */      $domains = array();     foreach ( $list as $l ) {          $arr = explode ( &quot;@&quot; , $l );          $domains [] = trim ( $arr [ 1 ]);     }      // remove duplicates and return      return array_unique ( $domains ); } // read email addresses from a file into an array $fileContents = file ( &quot;data.txt&quot; ); /* pass the file contents to the function and retrieve the result array */ $returnArray = getUniqueDomains ( $fileContents ); // process the return array foreach ( $returnArray as $d ) {     print &quot;$d, &quot; ; } ?> data.txt: [email_address] [email_address] [email_address] --output— yahoo.com, hotmail.com, cosmopoint.com,
  • 14. Marching arguments order Order in which arguments are passed to a function can be important. It will affect the value that will pass to the variables in function.
  • 15. Examples of argument order <?php // define a function function introduce ( $name , $place ) {     print &quot;Hello, I am $name from $place&quot; ; } // call function introduce ( &quot;Moonface&quot; , &quot;The Faraway Tree&quot; ); ?> The first value ‘Moonface’ will assign to the $name, while the “The Faraway Tree” will assign to the $place.
  • 16. Examples cont….. The output: introduce ( &quot;Moonface&quot; , &quot;The Faraway Tree&quot; ); Hello, I am Moonface from The Faraway Tree If you reversed the order in which arguments were passed to the function introduce ( &quot;The Faraway Tree Moonface&quot; , &quot;Moonface&quot; ); Hello, I am The Faraway Tree from Moonface If forgot to pass a required argument altogether Warning: Missing argument 2 for introduce() in xx.php on line 3 Hello, I am Moonface from
  • 17. Default value for arguments In order to avoid such errors, PHP allows the user to specify default values for all the arguments in a user-defined function. These default values are used if the function invocation is missing some arguments.
  • 18. Examples <?php // define a function function introduce ( $name = &quot;John Doe&quot; , $place = &quot;London&quot; ) {     print &quot;Hello, I am $name from $place&quot; ; } // call function introduce ( &quot;Moonface&quot; ); ?> ---Output Hello, I am Moonface from London The function has been called with only a single argument, even though the function definition requires two. New value will overwrite the default value, while the missing arguments will used the default value.
  • 19. Function functions All the examples on the previous page have one thing in common: the number of arguments in the function definition is fixed. PHP 4.x also supports variable-length argument lists, by using the func_num_args() and func_get_args() commands. These functions are called &quot;function functions&quot;.
  • 20. Example <?php // define a function function someFunc () {      // get the number of arguments passed      $numArgs = func_num_args ();     // get the arguments      $args = func_get_args ();      // print the arguments      print &quot;You sent me the following arguments: &quot; ;     for ( $x = 0 ; $x < $numArgs ; $x ++) {         print &quot;<br />Argument $x: &quot; ;          /* check if an array was passed and, if so, iterate and print contents */          if ( is_array ( $args [ $x ])) {             print &quot; ARRAY &quot; ;             foreach ( $args [ $x ] as $index => $element ) {                 print &quot; $index => $element &quot; ;             }         }         else {             print &quot; $args[$x] &quot; ;         }     } } // call a function with different arguments someFunc ( &quot;red&quot; , &quot;green&quot; , &quot;blue&quot; , array( 4 , 5 ), &quot;yellow&quot; ); ?> --output-- You sent me the following arguments: Argument 0: red Argument 1: green Argument 2: blue Argument 3: ARRAY 0 => 4 1 => 5 Argument 4: yellow
  • 21. Globals The global command allows the variable to be used outside the function after the function being invoked. To have variables within a function accessible from outside it (and vice-versa), declare the variables as &quot; global &quot;
  • 22. Example Without global command <?php // define a variable in the main program $today = &quot;Tuesday&quot; ; // define a function function getDay () {      // define a variable inside the function      $today = &quot;Saturday&quot; ;      // print the variable      print &quot;It is $today inside the function<br />&quot; ; } // call the function getDay (); // print the variable print &quot;It is $today outside the function&quot; ; ?> --output— It is Saturday inside the function It is Tuesday outside the function
  • 23. Example cont… With a global command <?php // define a variable in the main program $today = &quot;Tuesday&quot; ; // define a function function getDay () {      // make the variable global      global $today ;           // define a variable inside the function      $today = &quot;Saturday&quot; ;      // print the variable      print &quot;It is $today inside the function<br />&quot; ; } // print the variable print &quot;It is $today before running the function<br />&quot; ; // call the function getDay (); // print the variable print &quot;It is $today after running the function&quot; ; ?> ----output--- It is Tuesday before running the function It is Saturday inside the function It is Saturday after running the function
  • 24. Passing by value and reference There are two method in passing the arguments either by value or by reference. Passing arguments to a function &quot;by value&quot; - meaning that a copy of the variable was passed to the function, while the original variable remained untouched. PHP also allows method to pass &quot;by reference&quot; - meaning that instead of passing a value to a function, it pass a reference (pointer) to the original variable, and have the function act on that instead of a copy.
  • 25. Passing by value Example 1 <?php // create a variable $today = &quot;Saturday&quot; ; // function to print the value of the variable function setDay ( $day ) {      $day = &quot;Tuesday&quot; ;     print &quot;It is $day inside the function<br />&quot; ; } // call function setDay ( $today ); // print the value of the variable print &quot;It is $today outside the function&quot; ; ?> --output— It is Tuesday inside the function It is Saturday inside the function
  • 26. Passing by reference Example 2 <?php // create a variable $today = &quot;Saturday&quot; ; // function to print the value of the variable function setDay (& $day ) {      $day = &quot;Tuesday&quot; ;     print &quot;It is $day inside the function<br />&quot; ; } // call function setDay ( $today ); // print the value of the variable print &quot;It is $today outside the function&quot; ; ?> --output— It is Tuesday inside the function It is Tuesday outside the function
  • 27. Example 1 : The getDay() function is invoked, it passes the value &quot;Saturday&quot; to the function (&quot;passing by value&quot;). The original variable remains untouched; only its content is sent to the function. The function then acts on the content, modifying and displaying it. Example 2: Notice the ampersand (&) before the argument in the function definition. This tells PHP to use the variable reference instead of the variable value. When such a reference is passed to a function, the code inside the function acts on the reference, and modifies the content of the original variable (which the reference is pointing to) rather than a copy.
  • 28. The discussion about variables would be incomplete without mentioning the two ways of passing variables. This, of course, is what the global keyword does inside a function: use a reference to ensure that changes to the variable inside the function also reflect outside it. The PHP manual puts it best when it says &quot;...when you declare a variable as global $var you are in fact creating a reference to a global variable.