Lesson 6: Functions in PHP

Functions in PHP are reusable blocks of code that perform specific tasks. They help make code modular, efficient, and easier to debug. This lesson will explore defining and calling functions, working with parameters and return values, and understanding variable scope and global variables.


6.1 Defining and Calling Functions

What is a Function?

  • A function is a block of code that executes when called.
  • Functions can accept inputs (parameters) and return outputs.

Syntax

php
function functionName() {
// Code to be executed
}

Defining a Function

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

Calling a Function

php
<?php
sayHello(); // Outputs: Hello, World!
?>

Example: Function with a Task

php
<?php
function displayDate() {
echo "Today's date is " . date("Y-m-d") . "<br>";
}
displayDate(); // Outputs today’s date
displayDate(); // Can be reused
?>

6.2 Function Parameters and Return Values

Parameters

  • Parameters are variables passed to a function when it is called.
  • Syntax:
    php
    function functionName($param1, $param2) {
    // Code that uses $param1 and $param2
    }

Example: Function with Parameters

php
<?php
function greet($name) {
echo "Hello, $name!<br>";
}
greet(“Alice”); // Outputs: Hello, Alice!
greet(“Bob”); // Outputs: Hello, Bob!
?>

Default Parameter Values

  • Parameters can have default values.
  • Example:
    php
    <?php
    function greet($name = "Guest") {
    echo "Hello, $name!<br>";
    }
    greet(); // Outputs: Hello, Guest!
    greet(“Alice”); // Outputs: Hello, Alice!
    ?>

Return Values

  • A function can return a value using the return keyword.
  • Syntax:
    php
    function functionName($param) {
    return $value;
    }

Example: Function with Return Value

php
<?php
function add($a, $b) {
return $a + $b;
}
$result = add(5, 10); // Returns 15
echo “Sum: $result<br>”;
?>

Example: Function with Multiple Parameters and Return

php
<?php
function calculateArea($length, $width) {
return $length * $width;
}
$area = calculateArea(5, 10); // Returns 50
echo “Area: $area<br>”;
?>

Combining Parameters and Return Values

php
<?php
function calculateDiscount($price, $discountRate) {
$discount = $price * ($discountRate / 100);
return $price - $discount;
}
$finalPrice = calculateDiscount(100, 10); // Returns 90
echo “Final Price: $finalPrice<br>”;
?>

6.3 Variable Scope and Global Variables

What is Variable Scope?

Scope determines where a variable can be accessed. PHP has:

  1. Local Scope
  2. Global Scope
  3. Static Variables

Local Scope

  • Variables defined inside a function are local to that function.
  • Example:
    php
    <?php
    function testScope() {
    $localVar = "I'm local!";
    echo $localVar; // Accessible here
    }
    testScope(); // Outputs: I’m local
    // echo $localVar; // Error: Undefined variable
    ?>

Global Scope

  • Variables declared outside functions are global.
  • Example:
    php
    <?php
    $globalVar = "I'm global!";
    function testGlobal() {
    // echo $globalVar; // Error: Undefined variable
    }testGlobal();
    ?>

Accessing Global Variables Inside Functions

  • Use the global keyword or $GLOBALS array.
  • Example:
    php
    <?php
    $globalVar = "I'm global!";
    function accessGlobal() {
    global $globalVar;
    echo $globalVar; // Accessible here
    }accessGlobal(); // Outputs: I’m global!
    ?>
  • Example using $GLOBALS:
    php
    <?php
    $x = 5;
    $y = 10;
    function sumGlobal() {
    $sum = $GLOBALS[‘x’] + $GLOBALS[‘y’];
    echo “Sum: $sum<br>”;
    }sumGlobal(); // Outputs: Sum: 15
    ?>

Static Variables

  • Static variables retain their value between function calls.
  • Example:
    php
    <?php
    function counter() {
    static $count = 0;
    $count++;
    echo "Count: $count<br>";
    }
    counter(); // Outputs: Count: 1
    counter(); // Outputs: Count: 2
    counter(); // Outputs: Count: 3
    ?>

Activities and Exercises

  1. Defining and Calling Functions:
    • Write a function that takes your name as input and outputs “Welcome, [Name]!”
  2. Function Parameters:
    • Create a function to calculate the perimeter of a rectangle. It should take length and width as inputs.
  3. Return Values:
    • Write a function that calculates the compound interest and returns the final amount.
  4. Global Variables:
    • Write a script where a global variable tracks the total sales of a shop across multiple function calls.
  5. Static Variables:
    • Create a function that counts how many times it has been called.

Assignment

Write a PHP script that:

  1. Defines a function calculateGrade to calculate a student’s grade based on their score.
    • Parameters: score
    • Return: Grade (A, B, C, or F based on the score)
    • Criteria:
      • 90 and above: A
      • 75–89: B
      • 50–74: C
      • Below 50: F
  2. Accepts a student’s score as input and displays their grade.

Summary

In this lesson, you learned how to:

  • Define and call functions.
  • Work with function parameters and return values.
  • Understand variable scope, global variables, and static variables.

These concepts form the foundation for writing clean and modular PHP code. Let me know if you’d like additional examples or exercises!


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *