10 / 100 SEO Score

Chapter 3: Functions and Classes in PHP

In the last chapter, we explored arrays (indexed, associative, and multidimensional) and how to perform operations on them. Now, it’s time to level up and learn functions and classes, the two most powerful concepts in PHP.

Functions help us reuse code without writing it again and again, while classes help us organize code using object-oriented programming (OOP).


🎯 What You Will Learn

By the end of this chapter, you will be able to:

  • ✅ Define and call functions
  • ✅ Pass parameters and return values from functions
  • ✅ Create classes and objects
  • ✅ Use constructors, getters, and setters
  • ✅ Implement inheritance and static functions

🔹 Functions in PHP

A function is a block of code designed to perform a task. Instead of writing the same logic multiple times, you can wrap it in a function and reuse it whenever needed.

Basic Function Example:

<?php
function HelloWorld() {
    echo "Hello World";
}

HelloWorld(); // Calling the function
?>

Function with Parameters:

<?php
function HelloWorld($name) {
    echo "Hello World, " . $name;
}

HelloWorld("John");  // Output: Hello World, John
?>

Function with Default Parameter:

<?php
function displayMessage($message = "World") {
    echo "Hello " . $message;
}

displayMessage();        // Output: Hello World
displayMessage("Greg");  // Output: Hello Greg
?>

Function Returning a Value:

<?php
function addNumbers($a, $b) {
    return $a + $b;
}

echo addNumbers(5, 6); // Output: 11
?>

🛠️ Example: Discount Calculator

<?php
$sweaterPrice = 50;
$percentOff = 0.25;

function couponCode($price, $discount) {
    return $price * $discount;
}

echo "The sweater originally costs $" . $sweaterPrice .
     ". With discount, you’ll pay $" . 
     ($sweaterPrice - couponCode($sweaterPrice, $percentOff));
?>

🔹 Classes in PHP

A class is a blueprint for objects. It defines properties (variables) and methods (functions) that belong to the object.

Think of a class as a blueprint of a house and objects as actual houses built using that blueprint.

Basic Class Example:

<?php
class Student {
    public $name;
    public $age;
    public $major;
}

$michael = new Student();
$michael->name = "Michael John";
$michael->age = 27;
$michael->major = "Computer Science";

echo $michael->name; // Output: Michael John
?>

Constructor in Classes

A constructor is a special function that runs automatically when you create an object.

<?php
class Student {
    public $name;
    public $age;
    public $major;

    public function __construct($name, $age, $major) {
        $this->name = $name;
        $this->age = $age;
        $this->major = $major;
    }
}

$michael = new Student("Michael John", 27, "Computer Science");
echo $michael->name; // Output: Michael John
?>

Private Variables with Getters & Setters

To protect data, we can use private instead of public. Then, we use getters and setters to access/update them.

<?php
class Student {
    private $name;
    private $age;
    private $major;

    public function __construct($name, $age, $major) {
        $this->name = $name;
        $this->age = $age;
        $this->major = $major;
    }

    public function getMajor() {
        return $this->major;
    }

    public function setMajor($major) {
        $this->major = $major;
    }
}

$michael = new Student("Michael John", 27, "Computer Science");
$michael->setMajor("Engineering");
echo $michael->getMajor(); // Output: Engineering
?>

Inheritance in PHP

With inheritance, one class can extend another. For example:

<?php
class Animal {
    public $name;
    public $sound;

    public function speak() {
        echo $this->name . " says " . $this->sound;
    }
}

class Dog extends Animal {
    public $name = "Dog";
    public $sound = "Woof! Woof!";
}

$dog = new Dog();
$dog->speak(); // Output: Dog says Woof! Woof!
?>

Static Functions in PHP

Static functions belong to the class itself and not an object.

<?php
class Animal {
    public static function about() {
        echo "This is the animal base class.";
    }
}

Animal::about(); // Output: This is the animal base class.
?>

🛠️ Activity: Employee Monthly Pay Calculator

<?php
class BaseEmployee {
    private $name;
    private $title;
    private $salary;

    function __construct($name, $title, $salary) {
        $this->name = $name;
        $this->title = $title;
        $this->salary = $salary;
    }

    public function getSalary() {
        return $this->salary;
    }
}

class Employee extends BaseEmployee {
    public function calculateMonthlyPay() {
        return $this->getSalary() / 12;
    }
}

$markus = new Employee("Markus Gray", "CEO", 100000);
echo "Monthly Pay is $" . $markus->calculateMonthlyPay();
?>

📌 Summary

  • Functions help reuse code and return values.
  • Classes are blueprints for objects in PHP.
  • Public vs Private: controls how data can be accessed.
  • Constructors auto-run when creating objects.
  • Getters and Setters safely access private variables.
  • Inheritance allows extending base classes.
  • Static functions can be used without creating objects.

👉 In the next chapter, we’ll dive into data handling, input/output, error handling, and MySQL basics.

Leave a Comment