Welcome to the PHP Classes and Objects tutorial! By the end of this lesson, you'll be able to create your own reusable code blocks using PHP classes and objects. Let's get started!
In PHP, classes and objects are used to create reusable code. A class is a blueprint for creating objects, while an object is an instance of a class. It's like a recipe for baking a cake (class) and each individual cake (object) is made by following the recipe.
Let's create a simple class called Rectangle to calculate the area of a rectangle.
// Create a class called Rectangle
class Rectangle {
// Properties (attributes) of the class
public $width;
public $height;
// Constructor: runs when an object is created
function __construct($width, $height) {
$this->width = $width;
$this->height = $height;
}
// Method: calculates the area
function calculateArea() {
return $this->width * $this->height;
}
}π‘ Pro Tip: The constructor is used to initialize the properties of the class when an object is created.
Now, let's create an object of the Rectangle class.
// Create a new object called $myRectangle with the dimensions 5 and 3
$myRectangle = new Rectangle(5, 3);You can now use the object to calculate the area of the rectangle.
// Calculate the area of the rectangle
$area = $myRectangle->calculateArea();
echo "The area of the rectangle is: " . $area; // Output: The area of the rectangle is: 15One powerful feature of classes is inheritance, which allows one class to inherit properties and methods from another class. Let's create a Square class that inherits from Rectangle and sets the width and height to be the same.
// Create a class called Square that inherits from Rectangle
class Square extends Rectangle {
// Override the constructor to set the width and height to be the same
function __construct($side) {
parent::__construct($side, $side);
}
}Polymorphism allows objects of different classes to be treated as if they were of the same class. Let's create an AreaCalculator class that can calculate the area of both rectangles and squares.
class AreaCalculator {
// Method to calculate the area
function calculateArea($object) {
return $object->calculateArea();
}
}
// Create a new object of Rectangle and Square
$myRectangle = new Rectangle(5, 3);
$mySquare = new Square(4);
// Create a new object of AreaCalculator
$areaCalculator = new AreaCalculator();
// Calculate the area of both objects
echo "The area of the rectangle is: " . $areaCalculator->calculateArea($myRectangle) . "\n"; // Output: The area of the rectangle is: 15
echo "The area of the square is: " . $areaCalculator->calculateArea($mySquare) . "\n"; // Output: The area of the square is: 16What is the purpose of a constructor in a PHP class?
That's it for our PHP Classes and Objects tutorial! You now have the foundation to start creating your own reusable code blocks and understand the power of inheritance and polymorphism. Happy coding! π