PHP Classes and Objects

Understanding Object Oriented Programming

Object-Oriented Programming (OOP) is a programming paradigm centered around classes and objects. Unlike procedural programming, which focuses on functions manipulating data, OOP emphasizes creating objects that encapsulate both data and methods.

OOP offers several advantages over procedural programming:

  • It provides a structured modular approach to building programs.
  • It adheres to the "don't repeat yourself" (DRY) principle, reducing code duplication and improving maintainability.
  • It enables the creation of complex behaviors with fewer lines of code, shorter development cycles, and increased reusability.

The following sections will explain how classes and objects are implemented in PHP.

Tip: In procedural programming, programs consist of procedures, which are sets of statements that perform specific tasks.

Tip: The Don't Repeat Yourself (DRY) principle advocates for reducing code repetition by abstracting common code into reusable components.


Understanding Classes and Objects

Classes and objects are fundamental concepts in object-oriented programming (OOP). A class serves as a blueprint that encapsulates variables and functions designed to work together to achieve specific tasks. Objects, on the other hand, are instances of these classes.

A class functions as a template from which multiple objects can be instantiated. Each object inherits the general properties and behaviors defined in the class, while allowing for customization of specific attributes.

For example, imagine a class as a blueprint for a house. The blueprint itself isn't a house but provides detailed plans for constructing one. Objects are like actual houses built according to those plans. You can build many houses from the same blueprint, each with unique interiors, paint colors, and occupants, as depicted in the illustration below.

Class Object Relationship Illustration

To declare a class in PHP, use the class keyword followed by the class name and a pair of curly braces ({}), as demonstrated in the example below.

For instance, create a PHP file named Rectangle.php and place the following example code inside it. This approach ensures that our class code is isolated and can be reused by including the Rectangle.php file wherever needed.

Example

Download
<?php
class Rectangle
{
// Declare  properties
public $length = 0;
public $width = 0;

// Method to get the perimeter
public function getPerimeter(){
return (2 * ($this->length + $this->width));
}

// Method to get the area
public function getArea(){
return ($this->length * $this->width);
}
}
?>

The public keyword used before properties and methods in the example above serves as an access modifier, indicating that these properties or methods can be accessed from anywhere. We'll delve deeper into access modifiers later in this chapter.

Note: Within a class, variables are referred to as properties, while functions are known as methods. Class names conventionally use PascalCase, where each concatenated word begins with an uppercase letter (e.g., MyClass).

Once a class is defined, objects can be instantiated from it using the new keyword. Methods and properties of the class can then be accessed directly through instances of these objects.

To illustrate, create another PHP file named test.php and insert the following code:

<?php
// Include class definition
require "Rectangle.php";

// Create a new object from Rectangle class
$obj = new Rectangle;

// Get the object properties values
echo $obj->length; // 0utput: 0
echo $obj->width; // 0utput: 0

// Set object properties values
$obj->length = 30;
$obj->width = 20;

// Read the object properties values again to show the change
echo $obj->length; // 0utput: 30
echo $obj->width; // 0utput: 20


// Call the object methods
echo $obj->getPerimeter(); // 0utput: 100
echo $obj->getArea(); // Output: 600
?>

The arrow symbol (->) in object-oriented programming (OOP) is used to access properties and methods contained within a specific object. On the other hand, the pseudo-variable $this refers to the current object instance, allowing access to its methods and properties.

The true potential of object-oriented programming is demonstrated when using multiple instances of the same class, as illustrated below:

<?php
// Include class definition
require "Rectangle.php";

// Create multiple objects from the Rectangle class
$obj1 = new Rectangle;
$obj2 = new Rectangle;

// Call the methods of both the objects
echo $obj1->getArea(); // Output: 0
echo $obj2->getArea(); // Output: 0

// Set $obj1 properties values
$obj1->length = 30;
$obj1->width = 20;

// Set $obj2 properties values
$obj2->length = 35;
$obj2->width = 50;

// Call the methods of both the objects again
echo $obj1->getArea(); // Output: 600
echo $obj2->getArea(); // Output: 1750
?>

In the example above, invoking the getArea() method on different objects demonstrates how each method operates on distinct data sets. Each object instance is entirely independent, possessing its own unique properties and methods. Therefore, they can be manipulated separately, even if they belong to the same class.


Using Constructors and Destructors

To simplify object-oriented programming, PHP includes special methods that execute automatically when certain actions occur within an object.

For instance, the magic method __construct() (known as the constructor) runs automatically whenever a new object is created. Similarly, the magic method __destruct() (known as the destructor) is executed automatically when the object is destroyed. The destructor function handles the cleanup of any resources allocated to an object once it is no longer in use.

<?php
class MyClass
{
// Constructor
public function __construct(){
echo 'The class "' . __CLASS__ . '" was initiated!<br>';
}

// Destructor
public function __destruct(){
echo 'The class "' . __CLASS__ . '" was destroyed.<br>';
}
}

// Create a new object
$obj = new MyClass;

// Output a message at the end of the file
echo "The end of the file is reached.";
?>

The PHP code shown above will result in this output:

The class "MyClass" has been initialized!
The end of the file has been reached.
The class "MyClass" has been destroyed.

A destructor is automatically invoked when a script ends. However, you can explicitly trigger the destructor by using the PHP unset() function, like this:

<?php
class MyClass
{
// Constructor
public function __construct(){
echo 'The class "' . __CLASS__ . '" was initiated!<br>';
}

// Destructor
public function __destruct(){
echo 'The class "' . __CLASS__ . '" was destroyed.<br>';
}
}

// Create a new object
$obj = new MyClass;

// Destroy the object
unset($obj);

// Output a message at the end of the file
echo "The end of the file is reached.";
?>

The PHP code shown above will generate this output:

The class "MyClass" has been initialized!
The class "MyClass" has been destroyed.
The end of the file has been reached.

Tip: PHP automatically handles cleanup of all resources allocated during execution when the script finishes, such as closing database connections and destroying objects.

Note: The __CLASS__ is a magic constant that holds the name of the class where it is used. Outside of a class, it is empty.


Extending Classes with Inheritance

Classes can acquire the properties and methods of another class by using the extends keyword. This process, known as inheritance, enhances the flexibility of object-oriented programming. It allows classes to build upon existing ones, inheriting their functionality.

<?php
// Include class definition
require "Rectangle.php";

// Define a new class based on an existing class
class Square extends Rectangle
{   
// Method to test if the rectangle is also a square
public function isSquare(){
if($this->length == $this->width){
return true; // Square
} else{
return false; // Not a square
}
}
}

// Create a new object from Square class
$obj = new Square;

// Set object properties values
$obj->length = 20;
$obj->width = 20;

// Call the object methods
if($obj->isSquare()){
echo "The area of the square is ";
} else{
echo "The area of the rectangle is ";
};
echo $obj->getArea();
?>

The PHP code in the example above will result in the following output:

The area of the square is 400

As demonstrated, in the example, even though the Square class doesn't explicitly define the getArea() method or the $length and $width properties, instances of the Square class inherit them from the parent Rectangle class.

Tip: A child class derived from a parent class is also known as a derived class, while the parent class is referred to as the base class.


Controlling Access to Properties and Methods

When working with classes, you can control access to their properties and methods using visibility keywords. There are three levels of visibility: public, protected, and private. These keywords dictate where and how properties and methods can be accessed and modified.

  • public — Public properties or methods can be accessed from anywhere, both within the class and outside it. This is the default visibility for all class members in PHP.
  • protected — Protected properties or methods can only be accessed from within the class itself or by classes that inherit from it (child classes).
  • private — Private properties or methods are accessible only from within the class that defines them. They cannot be accessed by child classes or from outside the class.

The following example demonstrates how these visibility modifiers function:

Example

Download
<?php
// Class definition
class Automobile
{
// Declare  properties
public $fuel;
protected $engine;
private $transmission;
}
class Car extends Automobile
{
// Constructor
public function __construct(){
echo 'The class "' . __CLASS__ . '" was initiated!<br>';
}
}

// Create an object from Automobile class
$automobile = new Automobile;

// Attempt to set $automobile object properties
$automobile->fuel = 'Petrol'; // ok
$automobile->engine = '1500 cc'; // fatal error
$automobile->transmission = 'Manual'; // fatal error

// Create an object from Car class
$car = new Car;

// Attempt to set $car object properties
$car->fuel = 'Diesel'; // ok
$car->engine = '2200 cc'; // fatal error
$car->transmission = 'Automatic'; // undefined
?>

Static Properties and Methods

Apart from controlling visibility, properties and methods can also be marked as static. This allows them to be accessed without needing an instance of the class. Static properties and methods are accessed using the scope resolution operator (::), such as ClassName::$property and ClassName::method().

While a static method can be accessed using an object of the class, a static property cannot be, as illustrated in the example below:

Example

Download
<?php
// Class definition
class HelloClass
{
// Declare a static property
public static $greeting = "Hello World!";

// Declare a static method
public static function sayHello(){
echo self::$greeting;
}
}
// Attempt to access static property and method directly
echo HelloClass::$greeting; // Output: Hello World!
HelloClass::sayHello(); // Output: Hello World!

// Attempt to access static property and method via object
$hello = new HelloClass;
echo $hello->greeting; // Strict Warning
$hello->sayHello(); // Output: Hello World!
?>

In the example above, the keyword self refers to "the current class". It is used without a preceding dollar sign ($) and always followed by the :: operator (e.g. self::$name).

It's important to note that self differs from the this keyword, which refers to "the current object" or "the current instance of a class". The this keyword is used with a preceding dollar sign ($) and followed by the -> operator (e.g. $this->name).

Note: Since static methods can be called without an instance of a class (i.e., an object), the pseudo-variable $this is not available inside a static method.

We hope you now have a clear understanding of the fundamental concepts of object-oriented programming. You'll find more examples on OOP in the PHP and MySQL database section.