PHP Classes And Objects. Here’s What You Need To Know

Posted by TotalDC

Now let’s dive a bit deeper into PHP and learn about PHP classes and objects, what they are and why and how you should use them in in your everyday web development.

What Is Object Oriented Programming

Object oriented programming (OOP) is a programming model based on the concept of classes and objects. As opposed to procedural programming where you focus on writing procedures or functions that perform operations on the data, in object oriented programming the focus is on the creation of objects that contain both data and functions together.

There is several advantages of OOP over procedural programming. Here is some of the most important:

  • It provides a clear modular structure for the programs.
  • It helps you adhere to the “don’t repeat yourself” principle, and thus make your code much easier to maintain, modify and debug.
  • It makes it possible to create more complicated behavior with less code and shorter development time and high degree of reusability.

How To Understand Classes And Objects

Classes and objects are two main aspects of object oriented programming. A class is self-contained and independent collection of variables and functions which work together to perform one or more specific tasks, while objects are individual instances of a class.

Basically a class acts as a template from which multiple objects can be created. When objects are created, they inherit the same generic properties and behaviors but at the same time they can have different values or properties.

A class can be declared using class keyword followed by class name and pair of curly braces {} .

Now let”s create a PHP file named Rectangle.php and put the code from the example inside it. Then you can use it wherever it is needed by simply including the Rectangle.php file. If you are new to include and require statements you can find an article about them here.

Now let’s look at the example:

<?php
class Rectangle
{
    // Declare  properties
    public $length = 0;
    public $width = 0;
    
    // Get the perimeter
    public function getPerimeter(){
        return (2 * ($this->length + $this->width));
    }
    
    // Get the area
    public function getArea(){
        return ($this->length * $this->width);
    }
}
?>

What is public keyword you may be asking. The public keyword before the properties and methods in the example above is an access modifier which indicates that this property or method is accessible from anywhere in the code. Don’t worry, this topic will be covered later in this article.

Once a class has been defined, objects can be created from the class with the new keyword. Class methods and properties can directly be accessed through this object instance.

Now created another PHP file test.php and put the following code inside.

<?php
// Include class definition
require "Rectangle.php";
 
// Create a new object from Rectangle class
$obj = new Rectangle;
 
// Get the object properties values
print $obj->length; // 0utput: 0
print $obj->width; // 0utput: 0
 
// Set object properties values
$obj->length = 30;
$obj->width = 20;
 
// Read the object properties values again to show the change
print $obj->length; // 0utput: 30
print $obj->width; // 0utput: 20
 
 
// Call the object methods
print $obj->getPerimeter(); // 0utput: 100
print $obj->getArea(); // Output: 600
?>

Arrow symbol is and OOP construct that is used to access contained properties and methods of a given object. Pseudo-variable $this provides a reference to the calling object for example the object to which the method belongs.

You can see the real power of object oriented programming when using multiple instances of the same class, as shown in the following example:

<?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
print $obj1->getArea(); // Output: 0
print $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
print $obj1->getArea(); // Output: 600
print $obj2->getArea(); // Output: 1750
?>

As you can see in the example, calling the getArea() method on different objects causes that method to operate on a different set of data. Each object instance is completely independent, with its own properties and methods, and thus can be manipulated independently, even if they’re of the same class.

How To Use Constructors And Destructors

To make the object-oriented programming easier, PHP provides some methods that are executed automatically when certain actions occur within that object.

The __construct() constructor is executed automatically when a new object is created. Same __destruct() destructor is executed automatically when the object is destroyed. A destructor function cleans up any resources allocated to an object once the object is destroyed.

Here’s an example:

<?php
class MyClass
{
    // Constructor
    public function __construct(){
        print 'The class "' . __CLASS__ . '" was initiated!<br>';
    }
    
    // Destructor
    public function __destruct(){
        print 'The class "' . __CLASS__ . '" was destroyed.<br>';
    }
}
 
// Create object
$obj = new MyClass;
 
// Output 
print "The end of the file is reached.";
?>

Result of this example would be:

The class "MyClass" was initiated!
The end of the file is reached.
The class "MyClass" was destroyed.

Destructor is called automatically when your code ends. But to explicitly trigger the destructor you can destroy the object using the unset() function. Here’s and example of that:

<?php
class MyClass
{
    // Constructor
    public function __construct(){
        print 'The class "' . __CLASS__ . '" was initiated!<br>';
    }
    
    // Destructor
    public function __destruct(){
    print 'The class "' . __CLASS__ . '" was destroyed.<br>';
    }
}
 
// Create new object
$obj = new MyClass;
 
// Destroy object
unset($obj);
 
// Output
print "The end of the file is reached.";
?>

Result of this code would be:

The class "MyClass" was initiated!
The class "MyClass" was destroyed.
The end of the file is reached.

How To Extend Classes Through Inheritance

As you may know classes can inherit the properties and methods of another class using extends keyword. This is called inheritance. It is the one of the reasons of using the object oriented programming.

<?php
// Include class definition
require "Rectangle.php";
 
// Define new 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 new object
$obj = new Square;
 
// Set object properties values
$obj->length = 20;
$obj->width = 20;
 
// Call the object methods
if($obj->isSquare()){
    print "The area of the square is ";
} else{
    print "The area of the rectangle is ";
};
print $obj->getArea();
?>

Result:

The area of the square is 400

Even though the class definition of Square does not contain getArea() or $length or $width, Square class can use them because they are inherited from the parent Rectangle class.

Visibility Of Properties And Methods

You can restrict access of class properties and methods by using the visibility keywords. There are three of them: public, protected and private. They determines how and from where properties and methods can be accessed and modified.

  • public — A public property or method can be accessed anywhere, from within the class and outside. This is the default visibility for all class members in PHP.
  • protected — A protected property or method can only be accessed from within the class itself or in child or inherited classes i.e. classes that extends that class.
  • private — A private property or method is accessible only from within the class that defines it. Even child or inherited classes cannot access private properties or methods.

The following example shows you how this visibility works:

<?php
// Class definition
class Automobile
{
    // Declare  properties
    public $fuel;
    protected $engine;
    private $transmission;
}
class Car extends Automobile
{
    // Constructor
    public function __construct(){
        print 'The class "' . __CLASS__ . '" was initiated!<br>';
    }
}
 
// Create an object from Automobile class
$automobile = new Automobile;
 
// Set $automobile object properties
$automobile->fuel = 'Petrol'; // ok
$automobile->engine = '1500 cc'; // fatal error
$automobile->transmission = 'Manual'; // fatal error
 
// Create an object
$car = new Car;
 
// Set $car object properties
$car->fuel = 'Diesel'; // ok
$car->engine = '2200 cc'; // fatal error
$car->transmission = 'Automatic'; // undefined
?>

Static Properties And Methods

Properties and methods can be declared as static. If set to static they are accessible without the need of an instantiation of the class. Static properties and methods can be accessed by using scope resolution operator :: for example:

ClassName::$property
ClassName::method()

A property declared as static can’t be accessed via the object of that class but a static method can be.

<?php
// Class definition
class HelloClass
{
    // Declare static property
    public static $greeting = "Hello World!";
    
    // Declare static method
    public static function sayHello(){
        print self::$greeting;
    }
}
// Access static property and method directly
print HelloClass::$greeting; // Output: Hello World!
HelloClass::sayHello(); // Output: Hello World!
 
// Access static property and method via object
$hello = new HelloClass;
print $hello->greeting; // Strict Warning
$hello->sayHello(); // Output: Hello World!
?>

Keyword self in the example means – current class. It is never preceded by dollar sign $ and always is followed by :: operator. For example:

self::$name

The self keyword differs from this keyword. Keyword this is always preceded by a dollar sign $ and followed by the ->. For example:

$this->name

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: