SlideShare a Scribd company logo
PHP Functions
Outline
• Functions
• Function declaration
• Function Arguments
• Variable number of arguments
• Returning Values
• Variable Scope
• Static variables
• Recursion
• Tricks
• Useful Built-in Functions
• Assignment
Functions
• Is a sub program.
• A block of code that is defined under a certain name
( function name ).
• Can take arguments.
• Can return a value.
• Function name has the same naming rules as variables
and constants.
• Function names are not case sensitive.
Function declaration
function doSomething($arg_1, $arg_2, /* ..., */ $arg_n)
{
echo “something.n";
return $val;
}
Name Arguments
Body
Return
Function Arguments
• Passing by value (default – except for objects) :
function multiply($x, $y)
{
echo $x * $y;
}
Function Arguments
• Passing by reference :
$x = 10;
$y = 5;
$result = 0;
multiply( $x, $y , $result );
echo $result; // 50
function multiply($x, $y, &$result)
{
$result = $x * $y;
}
Function Arguments
• Default argument values:
function doIt( $name = “PHP” )
{
echo “Hello ” . $name;
}
Can be called :
doIt(); // Hello PHP
doIt( “Guys” ); // Hello Guys
• It is preferable that the arguments with default values
should be the last arguments passed to the function.
Function Arguments
• PHP emits a warning if the number of the arguments
passed is not the same the number of arguments in the
function declaration.
• PHP does not throw any warning in case the number is
bigger than the arguments in the function declaration.
function doIt( $name )
{
echo “Hello ” . $name;
}
doIt(); // a warning is emitted
doIt( “Elephant”, “Cow” ); // this is OK
Demo
Variable number of arguments
• PHP allows you to create a function with unlimited
number of arguments.
function displayAll( )
{
$numargs = func_num_args();
$arg_list = func_get_args();
for ($i = 0; $i < $numargs; $i++) {
echo $arg_list[$i] . “ ”;
}
}
displayAll( “This” , “is”, “a”, “good”, “thing.” );
Returning Values
• Functions may return values :
function doIt( $name )
{
return “Hello ” . $name;
}
echo doIt(“PHP”); // Hello PHP
Variable Scope
$a = 1; /* global scope */
function test()
{
echo $a; /* reference to local scope variable */
}
test(); // echoes an empty string
Variable Scope
The GLOBAL keyword:
$a = 1; /* global scope */
function test()
{
global $a; // can also use the $GLOBALS array
echo $a; /* reference to local scope variable */
}
test(); // 1
Static variables
• Static variables are initialized only one time.
function test()
{
static $a = 0;
echo $a;
$a++;
}
test(); //0
test(); // 1
test(); // 2
Recursion
• Recursion occurs when something contains, or uses, a
similar version of itself.
• In programming, it happens when a function is having
a call to itself.
• The factorial problem :
• 5! = 5 x 4 x 3 x 2 x 1 = 120
Recursion
function factorial($number) {
if ($number == 0) return 1;
return $number * factorial($number - 1);
}
echo factorial(6); // 720
Tricks
A function inside an IF statement :
if ($condition) {
function doSomething()
{
echo “Will only be defined if the IF condition is true";
}
// some code
doSomething();
}
Tricks
A function inside another function:
function doSomething1()
{
function doSomething2()
{
echo "I can only be called from inside doSomething1
n";
}
// some code
doSomething2();
}
Tricks
Variable functions:
function display( $x )
{
echo $x;
}
$name = “display”;
$name( “PHP” ); //PHP
Tricks
Anonymous functions:
$greet = function($name)
{
echo “Hello “ . $name;
};
$greet(“PHP”); // Hello PHP
Useful Built-in Functions
• boolean function_exists( $name )
• Checks whether there is a function with that
$name.
• void get_defined_functions()
• Gets a list of all names of defined functions in the
script.
Assignment
- Write a PHP function that calculates the average of passed
parameters (The number of parameters is dynamic).
What's Next?
• Arrays.
Questions?

More Related Content

What's hot

Form Handling using PHP
Form Handling using PHPForm Handling using PHP
Form Handling using PHP
Nisa Soomro
 
Chap 4 PHP.pdf
Chap 4 PHP.pdfChap 4 PHP.pdf
Chap 4 PHP.pdf
HASENSEID
 
Jsp/Servlet
Jsp/ServletJsp/Servlet
Jsp/Servlet
Sunil OS
 
Javascript variables and datatypes
Javascript variables and datatypesJavascript variables and datatypes
Javascript variables and datatypesVarun C M
 
Fundamental JavaScript [UTC, March 2014]
Fundamental JavaScript [UTC, March 2014]Fundamental JavaScript [UTC, March 2014]
Fundamental JavaScript [UTC, March 2014]
Aaron Gustafson
 
JavaScript Promises
JavaScript PromisesJavaScript Promises
JavaScript Promises
L&T Technology Services Limited
 
Angular Data Binding
Angular Data BindingAngular Data Binding
Angular Data Binding
Jennifer Estrada
 
Node.js Express
Node.js  ExpressNode.js  Express
Node.js Express
Eyal Vardi
 
Php forms
Php formsPhp forms
Php forms
Anne Lee
 
Php
PhpPhp
Introduction To PHP
Introduction To PHPIntroduction To PHP
Introduction To PHP
Shweta A
 
Php technical presentation
Php technical presentationPhp technical presentation
Php technical presentation
dharmendra kumar dhakar
 
Php functions
Php functionsPhp functions
Php functions
JIGAR MAKHIJA
 
Web api
Web apiWeb api
Delegates and events in C#
Delegates and events in C#Delegates and events in C#
Delegates and events in C#
Dr.Neeraj Kumar Pandey
 
9. ES6 | Let And Const | TypeScript | JavaScript
9. ES6 | Let And Const | TypeScript | JavaScript9. ES6 | Let And Const | TypeScript | JavaScript
9. ES6 | Let And Const | TypeScript | JavaScript
pcnmtutorials
 
Lab #2: Introduction to Javascript
Lab #2: Introduction to JavascriptLab #2: Introduction to Javascript
Lab #2: Introduction to Javascript
Walid Ashraf
 
PHP - DataType,Variable,Constant,Operators,Array,Include and require
PHP - DataType,Variable,Constant,Operators,Array,Include and requirePHP - DataType,Variable,Constant,Operators,Array,Include and require
PHP - DataType,Variable,Constant,Operators,Array,Include and require
TheCreativedev Blog
 
Loops PHP 04
Loops PHP 04Loops PHP 04
Loops PHP 04
Spy Seat
 

What's hot (20)

Form Handling using PHP
Form Handling using PHPForm Handling using PHP
Form Handling using PHP
 
Chap 4 PHP.pdf
Chap 4 PHP.pdfChap 4 PHP.pdf
Chap 4 PHP.pdf
 
Jsp/Servlet
Jsp/ServletJsp/Servlet
Jsp/Servlet
 
Javascript variables and datatypes
Javascript variables and datatypesJavascript variables and datatypes
Javascript variables and datatypes
 
Fundamental JavaScript [UTC, March 2014]
Fundamental JavaScript [UTC, March 2014]Fundamental JavaScript [UTC, March 2014]
Fundamental JavaScript [UTC, March 2014]
 
JavaScript Promises
JavaScript PromisesJavaScript Promises
JavaScript Promises
 
Angular Data Binding
Angular Data BindingAngular Data Binding
Angular Data Binding
 
Node.js Express
Node.js  ExpressNode.js  Express
Node.js Express
 
Php forms
Php formsPhp forms
Php forms
 
Php
PhpPhp
Php
 
Introduction To PHP
Introduction To PHPIntroduction To PHP
Introduction To PHP
 
Php technical presentation
Php technical presentationPhp technical presentation
Php technical presentation
 
Php functions
Php functionsPhp functions
Php functions
 
Web api
Web apiWeb api
Web api
 
Delegates and events in C#
Delegates and events in C#Delegates and events in C#
Delegates and events in C#
 
9. ES6 | Let And Const | TypeScript | JavaScript
9. ES6 | Let And Const | TypeScript | JavaScript9. ES6 | Let And Const | TypeScript | JavaScript
9. ES6 | Let And Const | TypeScript | JavaScript
 
Lab #2: Introduction to Javascript
Lab #2: Introduction to JavascriptLab #2: Introduction to Javascript
Lab #2: Introduction to Javascript
 
PHP - DataType,Variable,Constant,Operators,Array,Include and require
PHP - DataType,Variable,Constant,Operators,Array,Include and requirePHP - DataType,Variable,Constant,Operators,Array,Include and require
PHP - DataType,Variable,Constant,Operators,Array,Include and require
 
Loops PHP 04
Loops PHP 04Loops PHP 04
Loops PHP 04
 
PHP and Mysql
PHP and MysqlPHP and Mysql
PHP and Mysql
 

Viewers also liked

Php Tutorials for Beginners
Php Tutorials for BeginnersPhp Tutorials for Beginners
Php Tutorials for Beginners
Vineet Kumar Saini
 
Abstract Class and Interface in PHP
Abstract Class and Interface in PHPAbstract Class and Interface in PHP
Abstract Class and Interface in PHP
Vineet Kumar Saini
 
PHP Functions & Arrays
PHP Functions & ArraysPHP Functions & Arrays
PHP Functions & Arrays
Henry Osborne
 
Functions in php
Functions in phpFunctions in php
Functions in php
Mudasir Syed
 
Php tutorial
Php tutorialPhp tutorial
Php tutorialNiit
 

Viewers also liked (7)

Sorting arrays in PHP
Sorting arrays in PHPSorting arrays in PHP
Sorting arrays in PHP
 
Functions in PHP
Functions in PHPFunctions in PHP
Functions in PHP
 
Php Tutorials for Beginners
Php Tutorials for BeginnersPhp Tutorials for Beginners
Php Tutorials for Beginners
 
Abstract Class and Interface in PHP
Abstract Class and Interface in PHPAbstract Class and Interface in PHP
Abstract Class and Interface in PHP
 
PHP Functions & Arrays
PHP Functions & ArraysPHP Functions & Arrays
PHP Functions & Arrays
 
Functions in php
Functions in phpFunctions in php
Functions in php
 
Php tutorial
Php tutorialPhp tutorial
Php tutorial
 

Similar to Class 3 - PHP Functions

Licão 13 functions
Licão 13 functionsLicão 13 functions
Licão 13 functions
Acácio Oliveira
 
Functions in PHP.pptx
Functions in PHP.pptxFunctions in PHP.pptx
Functions in PHP.pptx
Japneet9
 
php AND MYSQL _ppt.pdf
php AND MYSQL _ppt.pdfphp AND MYSQL _ppt.pdf
php AND MYSQL _ppt.pdf
SVN Polytechnic Kalan Sultanpur UP
 
SPL: The Missing Link in Development
SPL: The Missing Link in DevelopmentSPL: The Missing Link in Development
SPL: The Missing Link in Developmentjsmith92
 
Introduction in php part 2
Introduction in php part 2Introduction in php part 2
Introduction in php part 2
Bozhidar Boshnakov
 
PHP 5.3 Overview
PHP 5.3 OverviewPHP 5.3 Overview
PHP 5.3 Overviewjsmith92
 
PHP-03-Functions.ppt
PHP-03-Functions.pptPHP-03-Functions.ppt
PHP-03-Functions.ppt
Jamers2
 
PHP-03-Functions.ppt
PHP-03-Functions.pptPHP-03-Functions.ppt
PHP-03-Functions.ppt
ShishirKantSingh1
 
What's new in PHP 8.0?
What's new in PHP 8.0?What's new in PHP 8.0?
What's new in PHP 8.0?
Nikita Popov
 
PHP - Introduction to PHP Functions
PHP -  Introduction to PHP FunctionsPHP -  Introduction to PHP Functions
PHP - Introduction to PHP Functions
Vibrant Technologies & Computers
 
JavaScript For CSharp Developer
JavaScript For CSharp DeveloperJavaScript For CSharp Developer
JavaScript For CSharp Developer
Sarvesh Kushwaha
 
Introducing PHP Latest Updates
Introducing PHP Latest UpdatesIntroducing PHP Latest Updates
Introducing PHP Latest UpdatesIftekhar Eather
 
DIG1108C Lesson 6 - Fall 2014
DIG1108C Lesson 6 - Fall 2014DIG1108C Lesson 6 - Fall 2014
DIG1108C Lesson 6 - Fall 2014
David Wolfpaw
 
Object Oriented PHP - PART-2
Object Oriented PHP - PART-2Object Oriented PHP - PART-2
Object Oriented PHP - PART-2
Jalpesh Vasa
 
Giới thiệu PHP 7
Giới thiệu PHP 7Giới thiệu PHP 7
Giới thiệu PHP 7
ZendVN
 
Let's JavaScript
Let's JavaScriptLet's JavaScript
Let's JavaScript
Paweł Dorofiejczyk
 
6976.ppt
6976.ppt6976.ppt
A Functional Guide to Cat Herding with PHP Generators
A Functional Guide to Cat Herding with PHP GeneratorsA Functional Guide to Cat Herding with PHP Generators
A Functional Guide to Cat Herding with PHP Generators
Mark Baker
 
Ch8(oop)
Ch8(oop)Ch8(oop)
Ch8(oop)
Chhom Karath
 

Similar to Class 3 - PHP Functions (20)

Licão 13 functions
Licão 13 functionsLicão 13 functions
Licão 13 functions
 
Functions in PHP.pptx
Functions in PHP.pptxFunctions in PHP.pptx
Functions in PHP.pptx
 
php AND MYSQL _ppt.pdf
php AND MYSQL _ppt.pdfphp AND MYSQL _ppt.pdf
php AND MYSQL _ppt.pdf
 
SPL: The Missing Link in Development
SPL: The Missing Link in DevelopmentSPL: The Missing Link in Development
SPL: The Missing Link in Development
 
Introduction in php part 2
Introduction in php part 2Introduction in php part 2
Introduction in php part 2
 
PHP 5.3 Overview
PHP 5.3 OverviewPHP 5.3 Overview
PHP 5.3 Overview
 
PHP-03-Functions.ppt
PHP-03-Functions.pptPHP-03-Functions.ppt
PHP-03-Functions.ppt
 
PHP-03-Functions.ppt
PHP-03-Functions.pptPHP-03-Functions.ppt
PHP-03-Functions.ppt
 
What's new in PHP 8.0?
What's new in PHP 8.0?What's new in PHP 8.0?
What's new in PHP 8.0?
 
PHP - Introduction to PHP Functions
PHP -  Introduction to PHP FunctionsPHP -  Introduction to PHP Functions
PHP - Introduction to PHP Functions
 
JavaScript For CSharp Developer
JavaScript For CSharp DeveloperJavaScript For CSharp Developer
JavaScript For CSharp Developer
 
Introduction to php basics
Introduction to php   basicsIntroduction to php   basics
Introduction to php basics
 
Introducing PHP Latest Updates
Introducing PHP Latest UpdatesIntroducing PHP Latest Updates
Introducing PHP Latest Updates
 
DIG1108C Lesson 6 - Fall 2014
DIG1108C Lesson 6 - Fall 2014DIG1108C Lesson 6 - Fall 2014
DIG1108C Lesson 6 - Fall 2014
 
Object Oriented PHP - PART-2
Object Oriented PHP - PART-2Object Oriented PHP - PART-2
Object Oriented PHP - PART-2
 
Giới thiệu PHP 7
Giới thiệu PHP 7Giới thiệu PHP 7
Giới thiệu PHP 7
 
Let's JavaScript
Let's JavaScriptLet's JavaScript
Let's JavaScript
 
6976.ppt
6976.ppt6976.ppt
6976.ppt
 
A Functional Guide to Cat Herding with PHP Generators
A Functional Guide to Cat Herding with PHP GeneratorsA Functional Guide to Cat Herding with PHP Generators
A Functional Guide to Cat Herding with PHP Generators
 
Ch8(oop)
Ch8(oop)Ch8(oop)
Ch8(oop)
 

More from Ahmed Swilam

Class 8 - Database Programming
Class 8 - Database ProgrammingClass 8 - Database Programming
Class 8 - Database Programming
Ahmed Swilam
 
Class 7 - PHP Object Oriented Programming
Class 7 - PHP Object Oriented ProgrammingClass 7 - PHP Object Oriented Programming
Class 7 - PHP Object Oriented Programming
Ahmed Swilam
 
Class 6 - PHP Web Programming
Class 6 - PHP Web ProgrammingClass 6 - PHP Web Programming
Class 6 - PHP Web Programming
Ahmed Swilam
 
Class 5 - PHP Strings
Class 5 - PHP StringsClass 5 - PHP Strings
Class 5 - PHP Strings
Ahmed Swilam
 
Class 4 - PHP Arrays
Class 4 - PHP ArraysClass 4 - PHP Arrays
Class 4 - PHP Arrays
Ahmed Swilam
 
Class 2 - Introduction to PHP
Class 2 - Introduction to PHPClass 2 - Introduction to PHP
Class 2 - Introduction to PHP
Ahmed Swilam
 
Class 1 - World Wide Web Introduction
Class 1 - World Wide Web IntroductionClass 1 - World Wide Web Introduction
Class 1 - World Wide Web Introduction
Ahmed Swilam
 

More from Ahmed Swilam (7)

Class 8 - Database Programming
Class 8 - Database ProgrammingClass 8 - Database Programming
Class 8 - Database Programming
 
Class 7 - PHP Object Oriented Programming
Class 7 - PHP Object Oriented ProgrammingClass 7 - PHP Object Oriented Programming
Class 7 - PHP Object Oriented Programming
 
Class 6 - PHP Web Programming
Class 6 - PHP Web ProgrammingClass 6 - PHP Web Programming
Class 6 - PHP Web Programming
 
Class 5 - PHP Strings
Class 5 - PHP StringsClass 5 - PHP Strings
Class 5 - PHP Strings
 
Class 4 - PHP Arrays
Class 4 - PHP ArraysClass 4 - PHP Arrays
Class 4 - PHP Arrays
 
Class 2 - Introduction to PHP
Class 2 - Introduction to PHPClass 2 - Introduction to PHP
Class 2 - Introduction to PHP
 
Class 1 - World Wide Web Introduction
Class 1 - World Wide Web IntroductionClass 1 - World Wide Web Introduction
Class 1 - World Wide Web Introduction
 

Recently uploaded

Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Jeffrey Haguewood
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
91mobiles
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
DianaGray10
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
Product School
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Product School
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
Product School
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
Kari Kakkonen
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
ControlCase
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
ThousandEyes
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
Ana-Maria Mihalceanu
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Albert Hoitingh
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Thierry Lestable
 
Generating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using SmithyGenerating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using Smithy
g2nightmarescribd
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
Sri Ambati
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
KatiaHIMEUR1
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Ramesh Iyer
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Inflectra
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
DanBrown980551
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
DianaGray10
 

Recently uploaded (20)

Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
 
Generating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using SmithyGenerating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using Smithy
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
 

Class 3 - PHP Functions

  • 2. Outline • Functions • Function declaration • Function Arguments • Variable number of arguments • Returning Values • Variable Scope • Static variables • Recursion • Tricks • Useful Built-in Functions • Assignment
  • 3. Functions • Is a sub program. • A block of code that is defined under a certain name ( function name ). • Can take arguments. • Can return a value. • Function name has the same naming rules as variables and constants. • Function names are not case sensitive.
  • 4. Function declaration function doSomething($arg_1, $arg_2, /* ..., */ $arg_n) { echo “something.n"; return $val; } Name Arguments Body Return
  • 5. Function Arguments • Passing by value (default – except for objects) : function multiply($x, $y) { echo $x * $y; }
  • 6. Function Arguments • Passing by reference : $x = 10; $y = 5; $result = 0; multiply( $x, $y , $result ); echo $result; // 50 function multiply($x, $y, &$result) { $result = $x * $y; }
  • 7. Function Arguments • Default argument values: function doIt( $name = “PHP” ) { echo “Hello ” . $name; } Can be called : doIt(); // Hello PHP doIt( “Guys” ); // Hello Guys • It is preferable that the arguments with default values should be the last arguments passed to the function.
  • 8. Function Arguments • PHP emits a warning if the number of the arguments passed is not the same the number of arguments in the function declaration. • PHP does not throw any warning in case the number is bigger than the arguments in the function declaration. function doIt( $name ) { echo “Hello ” . $name; } doIt(); // a warning is emitted doIt( “Elephant”, “Cow” ); // this is OK
  • 10. Variable number of arguments • PHP allows you to create a function with unlimited number of arguments. function displayAll( ) { $numargs = func_num_args(); $arg_list = func_get_args(); for ($i = 0; $i < $numargs; $i++) { echo $arg_list[$i] . “ ”; } } displayAll( “This” , “is”, “a”, “good”, “thing.” );
  • 11. Returning Values • Functions may return values : function doIt( $name ) { return “Hello ” . $name; } echo doIt(“PHP”); // Hello PHP
  • 12. Variable Scope $a = 1; /* global scope */ function test() { echo $a; /* reference to local scope variable */ } test(); // echoes an empty string
  • 13. Variable Scope The GLOBAL keyword: $a = 1; /* global scope */ function test() { global $a; // can also use the $GLOBALS array echo $a; /* reference to local scope variable */ } test(); // 1
  • 14. Static variables • Static variables are initialized only one time. function test() { static $a = 0; echo $a; $a++; } test(); //0 test(); // 1 test(); // 2
  • 15. Recursion • Recursion occurs when something contains, or uses, a similar version of itself. • In programming, it happens when a function is having a call to itself. • The factorial problem : • 5! = 5 x 4 x 3 x 2 x 1 = 120
  • 16. Recursion function factorial($number) { if ($number == 0) return 1; return $number * factorial($number - 1); } echo factorial(6); // 720
  • 17. Tricks A function inside an IF statement : if ($condition) { function doSomething() { echo “Will only be defined if the IF condition is true"; } // some code doSomething(); }
  • 18. Tricks A function inside another function: function doSomething1() { function doSomething2() { echo "I can only be called from inside doSomething1 n"; } // some code doSomething2(); }
  • 19. Tricks Variable functions: function display( $x ) { echo $x; } $name = “display”; $name( “PHP” ); //PHP
  • 20. Tricks Anonymous functions: $greet = function($name) { echo “Hello “ . $name; }; $greet(“PHP”); // Hello PHP
  • 21. Useful Built-in Functions • boolean function_exists( $name ) • Checks whether there is a function with that $name. • void get_defined_functions() • Gets a list of all names of defined functions in the script.
  • 22. Assignment - Write a PHP function that calculates the average of passed parameters (The number of parameters is dynamic).