0% found this document useful (0 votes)
10 views25 pages

UNIT II (Functions)

This document provides an overview of functions in PHP, detailing their purpose, types, and usage. It covers built-in and user-defined functions, variable scope, function parameters, return values, variable functions, anonymous functions, and date/time functions. The content emphasizes the importance of modularity, reusability, and maintainability in programming.

Uploaded by

ukesh bhattarai
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views25 pages

UNIT II (Functions)

This document provides an overview of functions in PHP, detailing their purpose, types, and usage. It covers built-in and user-defined functions, variable scope, function parameters, return values, variable functions, anonymous functions, and date/time functions. The content emphasizes the importance of modularity, reusability, and maintainability in programming.

Uploaded by

ukesh bhattarai
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 25

UNIT II (Functions)

Prepared By: Ukesh Bhattarai


Functions

 Functions are reusable blocks of code designed to perform specific


tasks.
 They enhance code modularity and readability, allowing developers to
write cleaner and more efficient programs.
 Modularity

Functions break down code into smaller,


manageable parts.
 Reusability

Functions can be used multiple times in a script.


 Maintainability

Changes within a function, do not affect the entire


program.
Types of functions

 Built-In functions:
 These are pre-defined functions provided by PHP.
 They cover a wide range of tasks, including string manipulation, mathematical operations,
and file handling.
 Examples include:
 String Functions
 Functions like strlen(), strpos(), and substr() manipulate strings.
<?php
echo substr("Hello world",6);
?>
 Math Functions
 Functions such as abs(), round(), and rand() perform math.
 Array Functions
 Functions like array_push(), array_pop(), and count() manage arrays.
 User-defined function
 These are custom functions created by developers to perform specific tasks.
 They allow for tailored functionality that can be reused throughout the application.

<?php
function greet() {
echo "Hello, World!";
}
greet();
?>
Defining a function

 To create a function in PHP, use the following syntax:


function functionName($parameter1, $parameter2, ...)
{
// Function code here
}
 Function Name: Must start with a letter or underscore and can contain
letters, numbers, and underscores.
 Parameters: Values passed into the function when it is called. You can
define multiple parameters separated by commas.
Calling a function

 Calling a function involves invoking its name followed by parentheses,


optionally passing any required arguments within those parentheses.
 This action executes the block of code defined within the function.
<?php
// Function definition
function greet() {
echo "Hello, World!";
}

// Function call
greet();
?>
Variable Scope

 Variable scope determines the accessibility and lifespan of a variable


within different parts of a program.
 Understanding variable scope is crucial for writing predictable and error-
free code.
 Local Scope
 Variables declared inside a function are considered to have a local scope.
 These variables are accessible only within that function and do not exist
outside of it.
<?php
function myFunction() {
$localVar = "I'm local";
echo $localVar; // Outputs: I'm local
}

myFunction();
echo $localVar; // Error: Undefined variable $localVar
?>
 Global Scope
 Variables declared outside of any function have a global scope.
 These variables are accessible from any part of the script except inside
functions, unless explicitly specified.
<?php
$globalVar = "I'm global";

function myFunction() {
echo $globalVar; // Error: Undefined variable $globalVar
}

myFunction();
echo $globalVar; // Outputs: I'm global
?>
 To access a global variable within a function, use the global keyword or
the $GLOBALS array.
<?php
$globalVar = "I'm global";

function myFunction() {
global $globalVar;
echo $globalVar; // Outputs: I'm global
}

myFunction();
?>
Static Variables
 Variables declared as static inside a function retain their value between function calls.
 This is useful for keeping track of information across multiple invocations of a function
without using global variables.
<?php
function myCounter() {
static $count = 0;
$count++;
echo $count;
}

myCounter(); // Outputs: 1
myCounter(); // Outputs: 2
myCounter(); // Outputs: 3
?>
Function Parameters
 Function parameters are variables specified in a function's declaration
that accept values, known as arguments, when the function is called.
 These parameters enable functions to process dynamic inputs,
enhancing code flexibility and reusability.
 Defining Function Parameters:
 Parameters are declared within the parentheses following the function name.
Multiple parameters are separated by commas.
<?php
function multiply($a, $b)
{
echo “$a * $b”;
}
?>
 Calling Functions with Arguments:
 When invoking a function, provide arguments corresponding to the defined
parameters.
<?php
multiply(5, 10);
?>
 Default Parameter Values:
 PHP allows default values for parameters, making them optional during function calls.

<?php
function greet($name = "Guest") {
echo "Hello, $name!";
}
greet(); // Outputs: Hello, Guest!
greet("Alice"); // Outputs: Hello, Alice!
?>
If no argument is provided, $name defaults to "Guest".
 Named Arguments (PHP 8.0+):
PHP 8.0 introduced named arguments, allowing you to specify arguments by
parameter name, enhancing readability and flexibility.
function configure($width = 100, $height = 200, $color = 'blue') {
}
configure($height: 300, $color: 'red');
 Type Declarations:
PHP supports type declarations for parameters, enforcing the type of arguments
passed to functions.

function add(int $a, int $b): int {


echo $a + $b;
}
echo add(5, 10); // Outputs: 15
Return Values
 Returns a result to use later – Unlike echo, return sends a value back.
 Stops function execution – Anything after return is ignored.
 Stores function output in variables – So you can use it elsewhere.
<?php
function addNumbers($a, $b) {
return $a + $b; // Returns the sum
}
echo "The sum is: " . addNumbers(5,10);
?>
 What happens without return?
<?php
function addNumbers($a, $b) {
echo $a + $b; // Directly prints the result
}
addNumbers(5,3);
echo "The sum is: " . addNumbers(5,3);
?>

Output: 8
The sum is:
Variable Functions

 A variable function in PHP allows you to call a function using a


variable.
 Instead of calling a function by its actual name, you store the function's
name in a variable and call it dynamically.
 Why Use Variable Functions?
They allow dynamic function execution (you decide at runtime which function to
call).
Helps create flexible and reusable code.
 Basic example
<?php
function greet() {
echo "Hello, PHP!";
}
$func = "greet"; // Assigning function name to a variable
$func(); // Calling function using variable
?>

Here, $func = "greet"; stores the function name in a variable, and $func();
calls that function dynamically.
 Example with parameters
<?php
function greet($name) {
echo "Hello, $name!";
}
$func = "greet";
$func("John"); // Calls greet("John")
?>
Here, $func("John"); dynamically calls greet("John").
 Selecting a Function Dynamically
Imagine a simple calculator where you choose an operation at
runtime.
<?php
function add($a, $b) {
return $a + $b;
}
function multiply($a, $b) {
return $a * $b;
}
$operation = "add";
echo $operation(5, 3); // Calls add(5, 3) and outputs 8

$operation = "multiply";
echo "<br>" . $operation(5, 3); // Calls multiply(5, 3) and outputs 15
?>
 When to Use Variable Functions?
Dynamic Function Calls – When the function name needs to be decided at
runtime.
Switching Between Functions – As seen in the calculator example.
Event Handling – Deciding what function to execute based on user input.
Anonymous Functions

 Anonymous functions (also called closures or lambda functions) are


functions without a name.
 Instead of defining a function with a name like function myFunction(),
you can create a function inside a variable or pass it directly as an
argument.
 Why Use Anonymous Functions?
Useful when you need a temporary function (one-time use).
Makes code cleaner and more readable when passing functions as
arguments.
 Basic Example of an Anonymous Function
Instead of defining a named function, we store a function inside a
variable.

<?php
$greet = function($name) {
return "Hello, $name!";
};
echo $greet("John");
?>
Here, $greet acts like a function name, but it’s actually a variable storing a
function.
We call it using $greet("John"); like a normal function.
 Using use() to Access Outer Variables
Since an anonymous function doesn’t have access to outside variables by
default, we use use() to pass them.
<?php
$multiplier = 3;

$multiply = function($num) use ($multiplier) {


return $num * $multiplier;
};

echo $multiply(5);
?>
The use ($multiplier) allows the function to access $multiplier from outside
its scope.
Date and Time Functions

 PHP provides built-in functions to work with date and time, allowing
developers to format, manipulate, and display date and time information
dynamically.
 The date() function is used to format and display the current date and time.
<?php
echo date("Y-m-d"); // Output: 2025-02-05 (Year-Month-Day)
?>

<?php
echo date("H:i:s"); // Output: 14:30:45 (Hour:Minute:Second)
?>

You might also like