Page Content

Tutorials

OOP In PHP: Classes, Objects, Constructors & Scope

Introduction to Object-Oriented Programming OOP in PHP

The coding technique known as object-oriented programming, or OOP, enables programmers to classify related jobs. It is an object-oriented programming language model. OOP aims to facilitate program development and code reuse by utilising the attributes, relationships, and classifications of the system’s objects. This method facilitates code reuse, encourages clean, modular architecture, and makes debugging and maintenance easier. An object-oriented approach is typically supported or even required by modern programming languages. PHP is said to be more relaxed, allowing developers to choose whether or not to build their scripts in an OOP approach, whereas other languages even mandate it.

Over time, PHP’s object-oriented features have changed. Beginning with PHP 5, the object model was revised to bring PHP closer to OOP standards. PHP 5 features a new and enhanced OOP approach along with a complete object model. All the characteristics of a completely object-oriented language are present in its OOP implementation.

Visibility, abstract and final classes and methods, extra magic methods, interfaces, cloning, and type-hinting are among the new features in PHP 5. The object model has been the focus of numerous recent PHP innovations. Although PHP is fundamentally a procedural language, it does support some OOP elements. Chapter 3 of “PHP 5 OOPLanguage” goes into great detail about PHP 5’s object-oriented features. Advanced OOP features are covered in Chapter 4 of the same book.

Basics of Classes and Objects

Almost any thing or idea can be considered an object in the context of OOP software. Software that is object-oriented is created and constructed as a collection of independent objects with interdependent properties and functions.

Understanding the mechanics of constructing a class and utilising the language constructs that support object-oriented programming, as well as knowing how to make objects interact in a way that results in maintainable code, are the two fundamental keys to comprehending how objects and classes operate.

A class is a data type that is specified by the programmer. It serves as a blueprint or template for creating things. A class is a definition of a structure that includes methods (functions) and attributes (variables). The fundamental units of object-oriented design are classes. The keyword class, followed by the class name and curly braces, is used in a minimal class definition:

Syntax:

class classname
{
    // Properties and methods go here
}

Class names have to follow PHP identifier guidelines.

A unique instance of the data structure specified by a class is called an object. The primary building blocks of object-oriented programming are objects and classes. After defining a class once, you create numerous objects that are part of it. Only once a class has been specified may objects be created. An object datatype will contain all of the class’s features and attributes when it is formed as a variable. Instances are another name for objects. Codes and data are combined to form objects.

Instantiating a class is another name for creating an object. You use the new keyword to construct an object. When you do this, you must indicate which class your object will be an instance of and supply any constructor-required parameters:

$obj = new MyClass(); // Creating an object of MyClass

Defining Properties (Members) and Methods

Classes require properties and operations in order to be useful.

The variables or data defined inside a class are called properties. Member variables or characteristics are other names for them. These variables can be accessed by member functions and will not be visible to those outside the class. Declaring variables inside a class definition allows you to define attributes:

Example:

class classname
{
    // Properties (variables)
    var $var1; // declared an undefined variable 
    var $var2 = 5; // declared a number defined variable
    var $var3 = "string"; // declared a string defined variable
}

Usually, an access modifier (which we shall cover under Scope) comes before variables inside a class definition.

The functions defined inside a class are called methods. They are sometimes referred to as operations or member functions. Object data is accessed by methods. Using normal function syntax, you define functions inside the class definition:

class classname
{
    // Properties
    var $var1;
    // Methods (functions)
    function myFunction ($argument1, $argument2) { // function definition 
        // function code here 
    }
}

The $this variable can be used to access properties and methods. A special variable called $this alludes to the same thing, or itself.
This is an example of a basic class that combines methods and properties:

<?php
class Dog {
    // Properties 
    public $breed; 
    public $name; 
    public $age; 
    // Methods 
    public function getInfo() {
        echo "I am $this->name, $this->age years old\n"; 
    }
}
// Create object 
$doggy = new Dog(); 
$doggy->name = "Tipsy"; 
$doggy->age = 7; 
// Call method
$doggy->getInfo();
?>

This example demonstrates how to define a method getInfo() that uses $this to retrieve the object’s properties and declare properties with public visibility.

Constructors and Destructors

A constructor is a unique kind of function that is automatically invoked whenever an object is formed from a class. They let you have certain functionality that will be used immediately after creating a class. A constructor function in PHP 5 needs to be called __construct(). Parameters can be passed to constructors.

The opposite of a constructor is a destructor. When all references to a class have been unset or have dropped out of scope, they enable you to have some code that will run right before the class is destroyed. A destructor function in PHP 5 needs to be called __destruct(). Destructors are incapable of accepting parameters. Be aware that PHP 5 is the only version with destructors.

An illustration of a constructor and destructor is provided here:

<?php
// define class 
class testClass {
    // PHP 5 constructor 
    function __construct() { 
        echo "Running the constructor \n";
    }
    // PHP 5 destructor 
    function __destruct() {
        echo "Running the destructor\n";  // Added the name property for demo 
    }
}
// create an object 
// result: "Running the constructor" 
$test = new testClass(); 
// then destroy it 
// result: "Running the destructor" 
unset($test); 
?>

Understanding Scope (Visibility)

The idea of visibility in the object model is supported by PHP. Visibility determines how open or closed a class is by limiting the caller’s ability to modify object properties and methods. There are three levels of visibility: secret, protected, and public keywords.

public:The class that declared the method or property, any classes that extend the declared class, and any external objects, classes, or code outside the class hierarchy can all access it when it is designated as public. The most noticeable level is this one. Although it is the default if no keyword is used, using other modifiers makes it easier to understand.

protected: both the base class definition and the inherited class definitions provide access to protected methods and properties. No external objects, classes, or code outside the class hierarchy can access them; only the class that declared them and the classes that extend the declared class can.

private: only the base class definition has access to private methods and properties. Only the class that defined it has access to them; external code or classes that extend it cannot. The least noticeable level is this one.

Script execution is stopped by a fatal error that occurs when private or protected properties or methods are attempted to be accessed outside of their visible region. Visibility constraints aid in encapsulating an object’s contents and improving the readability of object-oriented code.

<?php
class A {
    private function operation1() { 
        echo "operation1 called\n"; // Modified for clarity
    }
    protected function operation2() {
        echo "operation2 called\n"; // Modified for clarity
    }
    public function operation3() { 
        echo "operation3 called\n"; // Modified for clarity
    }
    // Public method to demonstrate access within the class
    public function callInternalMethods() {
        $this->operation1(); // OK (within declaring class)
        $this->operation2(); // OK (within declaring class)
        $this->operation3(); // OK (within declaring class)
    }
}
class B extends A { // B inherits from A 
    function __construct() { 
        // $this->operation1(); // Fatal Error: private method not accessible in child class
        $this->operation2(); // OK (within inherited class) 
        $this->operation3(); // OK (within inherited class) 
    }
    // Public method to demonstrate access within the child class
    public function callInheritedMethods() {
        // $this->operation1(); // Fatal Error
        $this->operation2(); // OK
        $this->operation3(); // OK
    }
}
// $a = new A();
// $a->operation1(); // Fatal Error: cannot access private method externally
// $a->operation2(); // Fatal Error: cannot access protected method externally
// $a->operation3(); // OK (can access public method externally)
$b = new B(); // Instantiating B, calls B's constructor 
// The constructor of B calls operation2() and operation3() which is allowed.
// $b->operation1(); // Fatal Error
// $b->operation2(); // Fatal Error
// $b->operation3(); // OK
?>

In contrast to protected and public, which are accessible in child classes and externally, private methods and properties are only accessible within their own class, as this code demonstrates.

Inheritance: Extending classes

The majority of object-oriented languages, including PHP, enable inheritance, a well-established programming concept. It indicates that all of a class’s features are automatically accessible to another class. Inheritance is the process by which a class is defined by taking over the functionality of a parent class.

The extends clause or keyword in PHP is used to create a parent/child connection between classes. This is the syntax:

class Child extends Parent {
    // definition body 
}

The parent class, base class, or super class is the class from which the inheritance is derived. The kid class, subclass, or derived class is the class that inherits.

<?php
// Parent class 
class Animal {
    public $name;
    public function __construct($name) {
        $this->name = $name;
    }
    public function eat() {
        echo "$this->name is eating.\n";
    }
}
// Child class extending Animal 
class Dog extends Animal { // Dog extends Animal
    public $breed;
    public function __construct($name, $breed) {
        parent::__construct($name); // Call parent constructor
        $this->breed = $breed;
    }
    // New method specific to Dog
    public function bark() {
        echo "$this->name ($this->breed) is barking.\n";
    }
    // Override the eat method
    public function eat() { // 
        echo "$this->name ($this->breed) is happily eating dog food.\n";
    }
}
// Create an instance of the child class
$myDog = new Dog("Buddy", "Golden Retriever");
// Access inherited properties (public) and methods
$myDog->eat(); // Calls the overridden method in Dog
$myDog->bark(); // Calls the new method in Dog
// Accessing property inherited from Animal
echo "My dog's name is " . $myDog->name . ".\n"; // Inherited public property
// If we had a parent method that wasn't overridden:
// $myDog->someInheritedMethod(); // Would call the method from Animal if it existed and was visible
?>

The child class inherits all or some of the parent class’s member functions and variables as a result of inheritance. An instance of the child class will inherit the parent class’s visible methods and attributes. This means the child class can access the parent class’s protected and public methods. Those methods will continue to function as intended unless they are overridden by a child class. Redefining a method that already exists in the parent class in the child class is known as overriding functionality.

By defining and abstracting functionality, inheritance makes it possible to introduce more functionality in related objects without having to reimplement all of the shared code.

This is an illustration of inheritance that makes use of the extends keyword:

In this instance, the eat() method and the $name attribute are passed down from the Animal class to the Dog class. It adds the method bark() and its own property $breed. Additionally, it alters the eat() method to provide dogs certain behaviour. To invoke the parent class’s constructor inside the constructor of the child class, use the parent:: syntax.

Index