Introduction:
In this PHP OOP tutorial, you’ll learn all about classes and objects, the fundamental building blocks of Object-Oriented Programming (OOP). We’ll focus on creating classes and objects,constructors, properties, and methods, inheritance, interfaces, static properties and methods, magic methods, and polymorphism. Additionally, we’ve created a quiz at the end to reinforce your understanding of PHP OOP concepts.
In PHP, The Object-Oriented Programming (OOP) focus on the concepts of classes and objects. Here’s a basic overview:
class Car { // Properties (attributes) public $brand; public $color; // Constructor public function __construct($brand, $color) { $this->brand = $brand; $this->color = $color; } // Method public function startEngine() { echo "Starting the engine of a {$this->color} {$this->brand} car."; } }
//How to Create objects $car1 = new Car("Toyota", "blue"); $car2 = new Car("BMW", "red"); // How to Access properties echo $car1->brand; // Output: Toyota echo $car2->color; // Output: red // How to Call methods $car1->startEngine(); // Output: Starting the engine of a blue Toyota car. $car2->startEngine(); // Output: Starting the engine of a red BMW car.
class ElectricCar extends Car { // Additional property public $batteryType; // Additional method public function chargeBattery() { echo "Charging the {$this->batteryType} battery of a {$this->color} {$this->brand} electric car."; } } // Creating an object of the subclass $electricCar = new ElectricCar("Tesla", "silver"); $electricCar->batteryType = "lithium-ion"; // Accessing inherited properties/methods echo $electricCar->brand; // Output: Tesla $electricCar->startEngine(); // Output: Starting the engine of a silver Tesla car. // Accessing subclass-specific properties/methods echo $electricCar->batteryType; // Output: lithium-ion $electricCar->chargeBattery(); // Output: Charging the lithium-ion battery of a silver Tesla electric car.
This is an explanation of PHP OOP with classes and objects.
There are many concepts and features in PHP OOP, such as encapsulation, polymorphism, interfaces, and abstract classes, which shows the power and flexibility of object-oriented programming in PHP.
Here is the process of creating PHP classes and objects step by step:
We need to define a class using the class keyword followed by the class name.
Inside the class, we can define properties and methods.
class Car { // Properties public $brand; public $color; // Methods public function startEngine() { return "Starting the engine of a {$this->color} {$this->brand} car."; } }
After defining the class, we can create objects (instances) of that class using the new keyword followed by the class name.
// Create objects $car1 = new Car(); $car2 = new Car();
We can set the properties of the objects using the arrow operator ->.
// How to Set properties for car1 $car1->brand = "Toyota"; $car1->color = "blue"; // How to Set properties for car2 $car2->brand = "BMW"; $car2->color = "red";
we can access the properties of objects in a similar way as setting them.
echo $car1->brand; // Output: Toyota echo $car2->color; // Output: red
We can call methods defined in the class for each object.
echo $car1->startEngine(); // Output: Starting the engine of a blue Toyota car. echo $car2->startEngine(); // Output: Starting the engine of a red BMW car.
class Car { // Properties public $brand; public $color; // Methods public function startEngine() { return "Starting the engine of a {$this->color} {$this->brand} car."; } } // Create objects $car1 = new Car(); $car2 = new Car(); // Set properties for car1 $car1->brand = "Toyota"; $car1->color = "blue"; // Set properties for car2 $car2->brand = "BMW"; $car2->color = "red"; // Access properties and call methods echo $car1->brand; // Output: Toyota echo $car2->color; // Output: red echo $car1->startEngine(); // Output: Starting the engine of a blue Toyota car. echo $car2->startEngine(); // Output: Starting the engine of a red BMW car.
That’s it! You’ve created a PHP class and instantiated objects from it, setting properties and calling methods on those objects.
Here’s a complete example about how to create a PHP class and using it in a web page with explanations:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Car Details</title> </head> <body> <h1>Car Details</h1> <?php // Include the Car class definition require_once 'Car.php'; // Create objects $car1 = new Car("Toyota", "blue"); $car2 = new Car("BMW", "red"); // Display car details echo "<h2>Car 1</h2>"; echo "<p>Brand: " . $car1->getBrand() . "</p>"; echo "<p>Color: " . $car1->getColor() . "</p>"; echo "<p>" . $car1->startEngine() . "</p>"; echo "<h2>Car 2</h2>"; echo "<p>Brand: " . $car2->getBrand() . "</p>"; echo "<p>Color: " . $car2->getColor() . "</p>"; echo "<p>" . $car2->startEngine() . "</p>"; ?> </body> </html>
<?php // Car.php class Car { // Properties private $brand; private $color; // Constructor public function __construct($brand, $color) { $this->brand = $brand; $this->color = $color; } // Getters public function getBrand() { return $this->brand; } public function getColor() { return $this->color; } // Method public function startEngine() { return "Starting the engine of a {$this->color} {$this->brand} car."; } } ?>
Explanation:
index.php is a web page that displays information about two cars.
It includes Car.php to access the Car class.
In Car.php, a class Car is defined with private properties $brand and $color.
The constructor __construct() sets the initial values of $brand and $color.
Getter methods getBrand() and getColor() are defined to access the private properties.
The method startEngine() returns a string indicating the car’s engine starting.
In index.php, two instances of Car class ($car1 and $car2) are created with different brand and color.
Car details are displayed using getter methods (getBrand() and getColor()) and the method startEngine().
When we run index.php in a web server, we’ll see a webpage that display the details of two cars, including their brand, color, and a message indicating the engine starting.
Here’s another example showing the creation of a PHP class and using it in a web page, step by step:
<?php // File: Animal.php class Animal { // Properties public $species; public $name; // Constructor public function __construct($species, $name) { $this->species = $species; $this->name = $name; } // Method public function makeSound() { return "The {$this->species} named {$this->name} makes a sound."; } } ?>
Explanation:
You’ve created a PHP class named Animal.
It has two public properties: $species and $name.
The constructor __construct() initializes these properties with the values passed as arguments.
There’s a method makeSound() that returns a string indicating the sound the animal makes.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Animal Sounds</title> </head> <body> <h1>Animal Sounds</h1> <?php // Include the Animal class definition require_once 'Animal.php'; // Create objects $animal1 = new Animal("Cat", "Whiskers"); $animal2 = new Animal("Dog", "Rex"); // Display animal sounds echo "<p>" . $animal1->makeSound() . "</p>"; echo "<p>" . $animal2->makeSound() . "</p>"; ?> </body> </html>
Explanation:
We’ve created an HTML page (index.php) that will display information about animals.
We include the Animal.php file for accessing the Animal class.
we created Two instances of the Animal class ($animal1 and $animal2) with different species and names.
We display the sounds made by these animals using the makeSound() method.
Save both Animal.php and index.php files in the same directory.
Start a PHP server (if not already running).
Navigate to index.php in web browser.
we should see a webpage titled “Animal Sounds” displaying the sounds made by a cat named Whiskers and a dog named Rex.
Summary:
This example shows the steps of creation of a PHP class (Animal) with properties and methods, and its usage in a web page to display information about different animals.
The class encapsulates the properties and behaviors related to animals, promoting code reusability and maintainability.
Here’s another example showing the creation of a PHP class and its usage within a web page,with step-by-step explanation:
<?php // File: Book.php class Book { // Properties public $title; public $author; public $year; // Constructor public function __construct($title, $author, $year) { $this->title = $title; $this->author = $author; $this->year = $year; } // Method to get book details public function getDetails() { return "{$this->title} by {$this->author}, published in {$this->year}"; } } ?>
Explanation:
We define a PHP class named Book.
This class contains three public properties: $title, $author, and $year.
The constructor __construct() initializes these properties with the values passed as arguments.
There’s a method getDetails() that returns a string containing the details of the book.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Book Information</title> </head> <body> <h1>Book Information</h1> <?php // Include the Book class definition require_once 'Book.php'; // Create objects $book1 = new Book("To Kill a Mockingbird", "Harper Lee", 1960); $book2 = new Book("The Great Gatsby", "F. Scott Fitzgerald", 1925); // Display book details echo "<h2>Book 1</h2>"; echo "<p>" . $book1->getDetails() . "</p>"; echo "<h2>Book 2</h2>"; echo "<p>" . $book2->getDetails() . "</p>"; ?> </body> </html>
Explanation:
We’ve created an HTML page (index.php) to display information about books.
We include the Book.php file to access the Book class.
Two instances of the Book class ($book1 and $book2) are created with different titles, authors, and publication years.
We display the details of each book using the getDetails() method.
Save both Book.php and index.php files in the same directory.
Start a PHP server if it’s not already running.
Navigate to index.php in your web browser.
You should see a webpage titled “Book Information” displaying details of two books.
Summary:
This example shows the steps of the creation of a PHP class (Book) and its usage within a web page to display information about different books.
The class encapsulates book properties and behaviors, assisting reusability of code and .
let’s start to create a complete PHP project based on Object-Oriented Programming (OOP) with step-by-step explanations.
In this project, we’ll create a system for managing books, including adding new books and listing existing ones.
Create a directory for your project and organize your files like this:
project/
│
├── classes/
│ └── Book.php
│
└── index.php
Create a file named Book.php inside the classes directory.
<?php class Book { // Properties public $title; public $author; public $year; // Constructor public function __construct($title, $author, $year) { $this->title = $title; $this->author = $author; $this->year = $year; } // Method to get book details public function getDetails() { return "{$this->title} by {$this->author}, published in {$this->year}"; } } ?>
Explanation:
We define a PHP class named Book.
This class contains three public properties: $title, $author, and $year.
The constructor __construct() initializes these properties with the values passed as arguments.
There’s a method getDetails() that returns a string containing the details of the book.
Create a file named index.php in the project directory.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Book Manager</title> </head> <body> <h1>Book Manager</h1> <?php // Include the Book class definition require_once 'classes/Book.php'; // Function to display all books function displayBooks($books) { echo "<h2>Books</h2>"; if (empty($books)) { echo "<p>No books available.</p>"; } else { echo "<ul>"; foreach ($books as $book) { echo "<li>" . $book->getDetails() . "</li>"; } echo "</ul>"; } } // Create some books $book1 = new Book("To Kill a Mockingbird", "Harper Lee", 1960); $book2 = new Book("The Great Gatsby", "F. Scott Fitzgerald", 1925); // Display the books displayBooks([$book1, $book2]); ?> </body> </html>
Explanation:
We include the Book.php file to access the Book class.
We define a function displayBooks() to display the details of all books.
We create two instances of the Book class ($book1 and $book2) with different titles, authors, and publication years.
We call the displayBooks() function to display the details of all books.
Save the files in their respective directories.
Start a PHP server if it’s not already running.
Navigate to index.php in your web browser.
we should see a webpage titled “Book Manager” displaying details of the two books.
Summary:
In this project, we’ve created a simple PHP project showing the use of classes and objects in Object-Oriented Programming. The Book class encapsulates book properties and behaviors, and the index.php file serves as the user interface to manage books. You can extend this project by adding more features such as adding new books, deleting books, or editing existing ones.
Here’s a PHP OOP quiz with 15 multiple-choice questions along with explanations:
A) To execute procedural code
B) To organize code into reusable components ✅
C) To improve code performance
Explanation: Classes and objects in PHP are used to organize code into reusable components, promoting modularity and maintainability.
A) instance
B) new ✅
C) create
Explanation: The new keyword is used to create an instance (object) of a class in PHP.
A) To destroy objects
B) To create new methods
C) To initialize object properties ✅
Explanation: The constructor in a PHP class is used to initialize the object’s properties when it is created.
A) this
B) object
C) -> ✅
Explanation: The -> arrow operator is used to access properties and methods of an object in PHP.
A) Using the function keyword ✅
B) Using the method keyword
C) Using the define keyword
Explanation: Methods inside a class in PHP are defined using the function keyword followed by the method name.
A) public
B) private ✅
C) protected
Explanation: The private access modifier makes a property or method accessible only within the same class in PHP.
A) Implement multiple interfaces
B) Extend functionality of another class ✅
C) Be instantiated directly
Explanation: Inheritance in PHP allows a class to inherit properties and methods from another class, thereby extending its functionality.
A) sealed
B) final ✅
C) closed
Explanation: The final keyword is used to prevent a class from being inherited in PHP.
A) serialize()
B) __serialize()
C) __sleep() ✅
Explanation: The __sleep() magic method is called when an object is serialized in PHP.
A) To create a new object
B) To serialize an object
C) To perform cleanup tasks before an object is destroyed ✅
Explanation: The __destruct() magic method is called automatically when an object is no longer referenced and about to be destroyed, allowing for cleanup tasks to be performed.
A) static
B) this
C) self ✅
Explanation: The self keyword is used to access static properties and methods within the same class in PHP.
A) When you want to access properties or methods from outside the class
B) When you want to create multiple instances of a class
C) When you want to share data across all instances of a class ✅
Explanation: The static keyword in PHP is used when you want to declare properties or methods that belong to the class itself rather than to instances of the class, allowing data to be shared across all instances.
A) To define the structure of a class ✅
B) To create new objects
C) To extend the functionality of a class
Explanation: An interface in PHP defines a contract that classes can implement, specifying the methods a class must implement.
A) use
B) implements ✅
C) extends
Explanation: The implements keyword is used to implement an interface in a class in PHP.
A) The ability of a method to have different implementations based on the calling object ✅
B) The ability to create multiple objects from the same class
C) The process of hiding the implementation details of a method
Explanation: Polymorphism in PHP refers to the ability of a method to have different implementations based on the calling object, allowing for flexibility and code reuse.