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)

Effective testing with pytest
Effective testing with pytestEffective testing with pytest
Effective testing with pytest
Hector Canto
 
Event Driven programming(ch1 and ch2).pdf
Event Driven programming(ch1 and ch2).pdfEvent Driven programming(ch1 and ch2).pdf
Event Driven programming(ch1 and ch2).pdf
AliEndris3
 
Advance Java Topics (J2EE)
Advance Java Topics (J2EE)Advance Java Topics (J2EE)
Advance Java Topics (J2EE)
slire
 
ORM in Django
ORM in DjangoORM in Django
ORM in Django
Hoang Nguyen
 
JavaScript - An Introduction
JavaScript - An IntroductionJavaScript - An Introduction
JavaScript - An Introduction
Manvendra Singh
 
Flask – Python
Flask – PythonFlask – Python
Flask – Python
Max Claus Nunes
 
Python/Flask Presentation
Python/Flask PresentationPython/Flask Presentation
Python/Flask Presentation
Parag Mujumdar
 
Django for Beginners
Django for BeginnersDjango for Beginners
Django for Beginners
Jason Davies
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
Vikash Singh
 
JavaScript
JavaScriptJavaScript
JavaScript
Vidyut Singhania
 
Basic Python Django
Basic Python DjangoBasic Python Django
Basic Python Django
Kaleem Ullah Mangrio
 
Django - Python MVC Framework
Django - Python MVC FrameworkDjango - Python MVC Framework
Django - Python MVC Framework
Bala Kumar
 
JavaScript - Chapter 15 - Debugging Techniques
 JavaScript - Chapter 15 - Debugging Techniques JavaScript - Chapter 15 - Debugging Techniques
JavaScript - Chapter 15 - Debugging Techniques
WebStackAcademy
 
Object oriented approach in python programming
Object oriented approach in python programmingObject oriented approach in python programming
Object oriented approach in python programming
Srinivas Narasegouda
 
JUnit 5
JUnit 5JUnit 5
JUnit 5
Scott Leberknight
 
Angular 8
Angular 8 Angular 8
Angular 8
Sunil OS
 
Node js introduction
Node js introductionNode js introduction
Node js introduction
Joseph de Castelnau
 
Introduction To C#
Introduction To C#Introduction To C#
Introduction To C#
SAMIR BHOGAYTA
 
Javascript
JavascriptJavascript
Javascript
Manav Prasad
 
Nodejs presentation
Nodejs presentationNodejs presentation
Nodejs presentation
Arvind Devaraj
 
Effective testing with pytest
Effective testing with pytestEffective testing with pytest
Effective testing with pytest
Hector Canto
 
Event Driven programming(ch1 and ch2).pdf
Event Driven programming(ch1 and ch2).pdfEvent Driven programming(ch1 and ch2).pdf
Event Driven programming(ch1 and ch2).pdf
AliEndris3
 
Advance Java Topics (J2EE)
Advance Java Topics (J2EE)Advance Java Topics (J2EE)
Advance Java Topics (J2EE)
slire
 
JavaScript - An Introduction
JavaScript - An IntroductionJavaScript - An Introduction
JavaScript - An Introduction
Manvendra Singh
 
Python/Flask Presentation
Python/Flask PresentationPython/Flask Presentation
Python/Flask Presentation
Parag Mujumdar
 
Django for Beginners
Django for BeginnersDjango for Beginners
Django for Beginners
Jason Davies
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
Vikash Singh
 
Django - Python MVC Framework
Django - Python MVC FrameworkDjango - Python MVC Framework
Django - Python MVC Framework
Bala Kumar
 
JavaScript - Chapter 15 - Debugging Techniques
 JavaScript - Chapter 15 - Debugging Techniques JavaScript - Chapter 15 - Debugging Techniques
JavaScript - Chapter 15 - Debugging Techniques
WebStackAcademy
 
Object oriented approach in python programming
Object oriented approach in python programmingObject oriented approach in python programming
Object oriented approach in python programming
Srinivas Narasegouda
 
Angular 8
Angular 8 Angular 8
Angular 8
Sunil OS
 

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
 
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
 
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 Sessoins N Cookies
Php Sessoins N CookiesPhp Sessoins N Cookies
Php Sessoins N Cookies
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
 
Prototype Utility Methods(1)
Prototype Utility Methods(1)Prototype Utility Methods(1)
Prototype Utility Methods(1)
mussawir20
 

Recently uploaded (20)

The No-Code Way to Build a Marketing Team with One AI Agent (Download the n8n...
The No-Code Way to Build a Marketing Team with One AI Agent (Download the n8n...The No-Code Way to Build a Marketing Team with One AI Agent (Download the n8n...
The No-Code Way to Build a Marketing Team with One AI Agent (Download the n8n...
SOFTTECHHUB
 
Unlocking Generative AI in your Web Apps
Unlocking Generative AI in your Web AppsUnlocking Generative AI in your Web Apps
Unlocking Generative AI in your Web Apps
Maximiliano Firtman
 
Integrating FME with Python: Tips, Demos, and Best Practices for Powerful Aut...
Integrating FME with Python: Tips, Demos, and Best Practices for Powerful Aut...Integrating FME with Python: Tips, Demos, and Best Practices for Powerful Aut...
Integrating FME with Python: Tips, Demos, and Best Practices for Powerful Aut...
Safe Software
 
The Changing Compliance Landscape in 2025.pdf
The Changing Compliance Landscape in 2025.pdfThe Changing Compliance Landscape in 2025.pdf
The Changing Compliance Landscape in 2025.pdf
Precisely
 
The Future of Cisco Cloud Security: Innovations and AI Integration
The Future of Cisco Cloud Security: Innovations and AI IntegrationThe Future of Cisco Cloud Security: Innovations and AI Integration
The Future of Cisco Cloud Security: Innovations and AI Integration
Re-solution Data Ltd
 
Challenges in Migrating Imperative Deep Learning Programs to Graph Execution:...
Challenges in Migrating Imperative Deep Learning Programs to Graph Execution:...Challenges in Migrating Imperative Deep Learning Programs to Graph Execution:...
Challenges in Migrating Imperative Deep Learning Programs to Graph Execution:...
Raffi Khatchadourian
 
Jignesh Shah - The Innovator and Czar of Exchanges
Jignesh Shah - The Innovator and Czar of ExchangesJignesh Shah - The Innovator and Czar of Exchanges
Jignesh Shah - The Innovator and Czar of Exchanges
Jignesh Shah Innovator
 
Kit-Works Team Study_아직도 Dockefile.pdf_김성호
Kit-Works Team Study_아직도 Dockefile.pdf_김성호Kit-Works Team Study_아직도 Dockefile.pdf_김성호
Kit-Works Team Study_아직도 Dockefile.pdf_김성호
Wonjun Hwang
 
Enterprise Integration Is Dead! Long Live AI-Driven Integration with Apache C...
Enterprise Integration Is Dead! Long Live AI-Driven Integration with Apache C...Enterprise Integration Is Dead! Long Live AI-Driven Integration with Apache C...
Enterprise Integration Is Dead! Long Live AI-Driven Integration with Apache C...
Markus Eisele
 
UiPath Agentic Automation: Community Developer Opportunities
UiPath Agentic Automation: Community Developer OpportunitiesUiPath Agentic Automation: Community Developer Opportunities
UiPath Agentic Automation: Community Developer Opportunities
DianaGray10
 
Agentic Automation - Delhi UiPath Community Meetup
Agentic Automation - Delhi UiPath Community MeetupAgentic Automation - Delhi UiPath Community Meetup
Agentic Automation - Delhi UiPath Community Meetup
Manoj Batra (1600 + Connections)
 
RTP Over QUIC: An Interesting Opportunity Or Wasted Time?
RTP Over QUIC: An Interesting Opportunity Or Wasted Time?RTP Over QUIC: An Interesting Opportunity Or Wasted Time?
RTP Over QUIC: An Interesting Opportunity Or Wasted Time?
Lorenzo Miniero
 
Zilliz Cloud Monthly Technical Review: May 2025
Zilliz Cloud Monthly Technical Review: May 2025Zilliz Cloud Monthly Technical Review: May 2025
Zilliz Cloud Monthly Technical Review: May 2025
Zilliz
 
AI 3-in-1: Agents, RAG, and Local Models - Brent Laster
AI 3-in-1: Agents, RAG, and Local Models - Brent LasterAI 3-in-1: Agents, RAG, and Local Models - Brent Laster
AI 3-in-1: Agents, RAG, and Local Models - Brent Laster
All Things Open
 
Does Pornify Allow NSFW? Everything You Should Know
Does Pornify Allow NSFW? Everything You Should KnowDoes Pornify Allow NSFW? Everything You Should Know
Does Pornify Allow NSFW? Everything You Should Know
Pornify CC
 
Transcript: Canadian book publishing: Insights from the latest salary survey ...
Transcript: Canadian book publishing: Insights from the latest salary survey ...Transcript: Canadian book publishing: Insights from the latest salary survey ...
Transcript: Canadian book publishing: Insights from the latest salary survey ...
BookNet Canada
 
Design pattern talk by Kaya Weers - 2025 (v2)
Design pattern talk by Kaya Weers - 2025 (v2)Design pattern talk by Kaya Weers - 2025 (v2)
Design pattern talk by Kaya Weers - 2025 (v2)
Kaya Weers
 
Mastering Testing in the Modern F&B Landscape
Mastering Testing in the Modern F&B LandscapeMastering Testing in the Modern F&B Landscape
Mastering Testing in the Modern F&B Landscape
marketing943205
 
AI You Can Trust: The Critical Role of Governance and Quality.pdf
AI You Can Trust: The Critical Role of Governance and Quality.pdfAI You Can Trust: The Critical Role of Governance and Quality.pdf
AI You Can Trust: The Critical Role of Governance and Quality.pdf
Precisely
 
How to Install & Activate ListGrabber - eGrabber
How to Install & Activate ListGrabber - eGrabberHow to Install & Activate ListGrabber - eGrabber
How to Install & Activate ListGrabber - eGrabber
eGrabber
 
The No-Code Way to Build a Marketing Team with One AI Agent (Download the n8n...
The No-Code Way to Build a Marketing Team with One AI Agent (Download the n8n...The No-Code Way to Build a Marketing Team with One AI Agent (Download the n8n...
The No-Code Way to Build a Marketing Team with One AI Agent (Download the n8n...
SOFTTECHHUB
 
Unlocking Generative AI in your Web Apps
Unlocking Generative AI in your Web AppsUnlocking Generative AI in your Web Apps
Unlocking Generative AI in your Web Apps
Maximiliano Firtman
 
Integrating FME with Python: Tips, Demos, and Best Practices for Powerful Aut...
Integrating FME with Python: Tips, Demos, and Best Practices for Powerful Aut...Integrating FME with Python: Tips, Demos, and Best Practices for Powerful Aut...
Integrating FME with Python: Tips, Demos, and Best Practices for Powerful Aut...
Safe Software
 
The Changing Compliance Landscape in 2025.pdf
The Changing Compliance Landscape in 2025.pdfThe Changing Compliance Landscape in 2025.pdf
The Changing Compliance Landscape in 2025.pdf
Precisely
 
The Future of Cisco Cloud Security: Innovations and AI Integration
The Future of Cisco Cloud Security: Innovations and AI IntegrationThe Future of Cisco Cloud Security: Innovations and AI Integration
The Future of Cisco Cloud Security: Innovations and AI Integration
Re-solution Data Ltd
 
Challenges in Migrating Imperative Deep Learning Programs to Graph Execution:...
Challenges in Migrating Imperative Deep Learning Programs to Graph Execution:...Challenges in Migrating Imperative Deep Learning Programs to Graph Execution:...
Challenges in Migrating Imperative Deep Learning Programs to Graph Execution:...
Raffi Khatchadourian
 
Jignesh Shah - The Innovator and Czar of Exchanges
Jignesh Shah - The Innovator and Czar of ExchangesJignesh Shah - The Innovator and Czar of Exchanges
Jignesh Shah - The Innovator and Czar of Exchanges
Jignesh Shah Innovator
 
Kit-Works Team Study_아직도 Dockefile.pdf_김성호
Kit-Works Team Study_아직도 Dockefile.pdf_김성호Kit-Works Team Study_아직도 Dockefile.pdf_김성호
Kit-Works Team Study_아직도 Dockefile.pdf_김성호
Wonjun Hwang
 
Enterprise Integration Is Dead! Long Live AI-Driven Integration with Apache C...
Enterprise Integration Is Dead! Long Live AI-Driven Integration with Apache C...Enterprise Integration Is Dead! Long Live AI-Driven Integration with Apache C...
Enterprise Integration Is Dead! Long Live AI-Driven Integration with Apache C...
Markus Eisele
 
UiPath Agentic Automation: Community Developer Opportunities
UiPath Agentic Automation: Community Developer OpportunitiesUiPath Agentic Automation: Community Developer Opportunities
UiPath Agentic Automation: Community Developer Opportunities
DianaGray10
 
RTP Over QUIC: An Interesting Opportunity Or Wasted Time?
RTP Over QUIC: An Interesting Opportunity Or Wasted Time?RTP Over QUIC: An Interesting Opportunity Or Wasted Time?
RTP Over QUIC: An Interesting Opportunity Or Wasted Time?
Lorenzo Miniero
 
Zilliz Cloud Monthly Technical Review: May 2025
Zilliz Cloud Monthly Technical Review: May 2025Zilliz Cloud Monthly Technical Review: May 2025
Zilliz Cloud Monthly Technical Review: May 2025
Zilliz
 
AI 3-in-1: Agents, RAG, and Local Models - Brent Laster
AI 3-in-1: Agents, RAG, and Local Models - Brent LasterAI 3-in-1: Agents, RAG, and Local Models - Brent Laster
AI 3-in-1: Agents, RAG, and Local Models - Brent Laster
All Things Open
 
Does Pornify Allow NSFW? Everything You Should Know
Does Pornify Allow NSFW? Everything You Should KnowDoes Pornify Allow NSFW? Everything You Should Know
Does Pornify Allow NSFW? Everything You Should Know
Pornify CC
 
Transcript: Canadian book publishing: Insights from the latest salary survey ...
Transcript: Canadian book publishing: Insights from the latest salary survey ...Transcript: Canadian book publishing: Insights from the latest salary survey ...
Transcript: Canadian book publishing: Insights from the latest salary survey ...
BookNet Canada
 
Design pattern talk by Kaya Weers - 2025 (v2)
Design pattern talk by Kaya Weers - 2025 (v2)Design pattern talk by Kaya Weers - 2025 (v2)
Design pattern talk by Kaya Weers - 2025 (v2)
Kaya Weers
 
Mastering Testing in the Modern F&B Landscape
Mastering Testing in the Modern F&B LandscapeMastering Testing in the Modern F&B Landscape
Mastering Testing in the Modern F&B Landscape
marketing943205
 
AI You Can Trust: The Critical Role of Governance and Quality.pdf
AI You Can Trust: The Critical Role of Governance and Quality.pdfAI You Can Trust: The Critical Role of Governance and Quality.pdf
AI You Can Trust: The Critical Role of Governance and Quality.pdf
Precisely
 
How to Install & Activate ListGrabber - eGrabber
How to Install & Activate ListGrabber - eGrabberHow to Install & Activate ListGrabber - eGrabber
How to Install & Activate ListGrabber - eGrabber
eGrabber
 

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.
  翻译: