PHP Object-Oriented Programming with Examples

A programming paradigm known as object-oriented programming (OOP) in PHP enables programmers to arrange code into objects that represent real-world entities or concepts. In OOP, classes are blueprints that specify the properties and behaviors of the objects, and objects are instances of those classes.

In this post, I'm going to cover the following topics under the concept of object-oriented programming in PHP:

PHP OOP: classes and objects

Classes and objects are essential components of object-oriented programming in PHP. A class is a blueprint for creating objects, whereas an object is a class instance.

In PHP, you define a class by using the "class" keyword followed by the class name, and then defining the properties and methods within curly braces. Here's an illustration:

PHP Code
<?php 
   class MyClass {
      public $name;
      public $city;
      public $state;
      
      public function message() {
         echo "Hello there! I'm $this->name, and I live in $this->city, $this->state.<BR>";
      }
   }

   $x = new MyClass;
   $x->name = "William";
   $x->city = "Houston";
   $x->state = "Texas";
   $x->message();
?>
Output
Hello there! I'm William, and I live in Houston, Texas.

The $name, $city, and $state public properties of the "MyClass" class are defined in this PHP code. Additionally, the class has a public method called "message" that generates a welcome message that contains the values of the properties.

Following the class definition, the code instantiates a new MyClass object using the new keyword and assigns it to the variable $x. Then, using the arrow notation "->," the code sets the values of the object's properties. The greeting message is then output using the values of the properties that were previously set when the $x object's "message" method is finally invoked.

You can create as many objects of a class as you need, each with its own set of properties and the ability to call its own methods independently of other objects of the same class. As an example:

PHP Code
<?php 
   class MyClass {
      public $name;
      public $city;
      public $state;
      
      public function message() {
         echo "<p>Hello there!</p>";
         echo "<p>My name is: $this->name</p>";
         echo "<p>I live in: $this->city, $this->state</p>";
         echo "<p>---------------------------------</p>";
      }
   }

   $a = new MyClass;
   $a->name = "William";
   $a->city = "Houston";
   $a->state = "Texas";
   $a->message();
   
   $b = new MyClass;
   $b->name = "Edwin";
   $b->city = "Orlando";
   $b->state = "Florida";
   $b->message();
   
   $c = new MyClass;
   $c->name = "Lucas";
   $c->city = "Tucson";
   $c->state = "Arizona";
   $c->message();
?>
Output
Hello there!

My name is: William

I live in: Houston, Texas

---------------------------------

Hello there!

My name is: Edwin

I live in: Orlando, Florida

---------------------------------

Hello there!

My name is: Lucas

I live in: Tucson, Arizona

---------------------------------

PHP this keyword

The PHP "this" keyword refers to the active object of a class. The arrow operator "->" lets you access a class's properties and methods after creating an object.

PHP member function

An internal function that can be called on a class instance in PHP is known as a member function. It can also be referred to as a method. Using the "this" keyword, member functions have access to and control over the properties (variables) of the object they are called on. Members can now perform operations on the object, like setting or retrieving its state. In the above example, "message()" is a member function of the class "MyClass."

PHP member variable

An internal class variable that is linked to a class instance is referred to as a member variable in PHP. It can also be referred to as a property. Data that is particular to an object is stored in member variables. The member variables are replicated in each object of the class and can be accessed and changed by the member functions of that class by using the "this" keyword. In the above example, $name, $city, and $state are member variables.

PHP instanceof keyword

The "instanceof" operator in PHP is used to determine whether or not an object is an instance of a specific class. Depending on whether the object is an instance of the class or not, the operator returns a boolean value of "true" or "false," respectively. As an example:

PHP Code
<?php 
   class ClassOne {
      public $x;
   }
   class ClassTwo {
      public $x;
   }

   $a = new ClassOne;       // creates an object $a of the class ClassOne
   $b = new ClassTwo;       // creates an object $b of the class ClassTwo
   
   $resOne = $a instanceof ClassOne;
   $resTwo = $b instanceof ClassOne;
   
   echo var_dump($resOne);
   echo "<BR>";
   echo var_dump($resTwo);
?>
Output
bool(true)
bool(false)

This PHP code declares two classes named "ClassOne" and "ClassTwo," each of which has an "x" public property. Then, it creates "$a" and "$b" objects of "ClassOne" and "ClassTwo," respectively. The code then uses the "instanceof" operator to determine whether the objects are "ClassOne" instances. Each "instanceof" operation's result is assigned to the variables "$resOne" and "$resTwo." The "var dump" function is then used to output the values of "$resOne" and "$resTwo." "$a" is an instance of "ClassOne," so "$resOne" is set to "true," which is output by "var dump" as "bool(true)." In contrast, "$b" is not an instance of "ClassOne," so "$resTwo" is set to "false," which "var dump" outputs as "bool(false)."

PHP class and object example

Let me include one last example demonstrating the class and object in PHP before closing the discussion on it.

PHP Code
<?php 
   class CodeCracker {
      public static function message() {
         echo "Welcome to CodeCracker, the ultimate resource for learning to code!";
      }
   }
   CodeCracker::message();
?>
Output
Welcome to CodeCracker, the ultimate resource for learning to code!

"CodeCracker" is a PHP class with a static "message" method. The "message" method simply prints the specified text using the "echo" statement. "public" and "static" define the method's visibility and scope. "public" means the method can be called outside the class, and "static" means it can be called without creating a "CodeCracker" instance. Instead, the scope resolution operator (::) on the class name calls it. Finally, the scope resolution operator on "CodeCracker" calls the "message" method. It displays the written text using the "echo" statement when executed.

PHP access modifiers

The visibility or accessibility of class properties and methods is determined by three access modifiers in PHP:

Consider the following PHP code as an example of the access modifiers in PHP:

class MyClass {
   public $publicProperty;             // can be accessed from anywhere in the program
   protected $protectedProperty;       // can only be accessed within this class and its subclasses
   private $privateProperty;           // can only be accessed within this class

    public function publicMethod() {   // can be accessed from anywhere in the program
        // block of code to define this method
    }

    protected function protectedMethod() {   // can be accessed within the class and its subclasses
        // block of code to define this method
    }

    private function privateMethod() {       // can only be accessed within the class
        // block of code to define this method
    }
}

PHP OOP: constructor and destructor

When an object of a given class is created, PHP automatically invokes a special member function known as the class's constructor. The constructor is defined using the "__construct" keyword. As an example:

PHP Code
<?php 
   class MyClass {
      public function __construct() {
         echo "Object created!";
      }
   }

   $ob = new MyClass();
?>
Output
Object created!

In this PHP code, a class named MyClass is defined with a constructor method __construct(). The constructor method is executed automatically when an object of the class is created using the "new" keyword.

When an object is destroyed, either explicitly using the "unset" function or when the PHP script completes its execution, a special member function called destructor is automatically called. The destructor method has the name "__destruct." As an example:

PHP Code
<?php 
   class MyClass {
      public function __construct() {
         echo "Object created!";
      }
      public function __destruct() {
         echo "Object destroyed!";
      }
   }

   $ob = new MyClass();
?>
Output
Object created!Object destroyed!

Here is another example to boost your skills on constructors and destructors in PHP.

PHP Code
<?php 
   class MyClass {
      public function __construct() {
         echo "Object created!";
      }
      public function __destruct() {
         echo "Object destroyed!";
      }
   }

   $obOne = new MyClass();
   $obTwo = new MyClass();
?>
Output
Object created!Object created!Object destroyed!Object destroyed!

In this PHP code, a class named MyClass is defined with a constructor method __construct() and a destructor method __destruct(). The constructor method is executed automatically when an object of the class is created using the "new" keyword, and the destructor method is executed automatically when the object is destroyed or goes out of scope.

In the code, two objects $obOne and $obTwo of the MyClass are created using the constructor method __construct(). When the objects are created, the constructor method is executed for each of them and the string "Object created!" is echoed to the screen. Then, when the script execution ends, the destructor method is executed for each of the objects and the string "Object destroyed!" is echoed to the screen. Now let me use the "unset" method to destroy the object before the PHP script finishes its execution.

PHP Code
<?php 
   class MyClass {
      public function __construct() {
         echo "Object created!";
      }
      public function __destruct() {
         echo "Object destroyed!";
      }
   }

   $obOne = new MyClass();
   unset($obOne);
   $obTwo = new MyClass();
?>
Output
Object created!Object destroyed!Object created!Object destroyed!

The unset() function is used to destroy the $obOne object explicitly. When unset($obOne) is executed, the destructor method __destruct() is called automatically, which echoes the string "Object destroyed!" to the screen. Finally, a second object of the MyClass class is created and assigned to the variable $obTwo. The constructor method is called for this object, which echoes the string "Object created!" to the screen, and then the desctructor is called when the PHP script finishes execution.

PHP OOP: inheritance

The ability to define a new class based on an existing class, known as the parent or base class, is made possible by inheritance, a crucial object-oriented concept in PHP. The new class, also known as the child class or derived class, receives all of the attributes and methods from the parent class in addition to the option to add new attributes and methods that are not present in the parent class or to override those that are.

Using the "extends" keyword when defining a new class in PHP enables inheritance. As an illustration:

PHP Code
<?php 
   class Animal {
      public function eat() {
         echo "<p>The animal is eating.</p>";
      }
   }

   class Cat extends Animal {
      public function meow() {
         echo "<p>The cat is meowing.</p>";
      }
   }

   $ob = new Cat();
   $ob->eat();
   $ob->meow();
?>
Output
The animal is eating.

The cat is meowing.

This is a block of PHP code that defines two classes, Animal and Cat, and creates an object of the Cat class to call its methods. The Animal class is defined first and has a single method called eat(), which simply outputs the text "The animal is eating" wrapped in a paragraph tag. The Cat class is then defined using the extends keyword to indicate that it is a subclass of Animal. It has its own method called meow(), which outputs the text "The cat is meowing" wrapped in a paragraph tag.

After the classes are defined, an object of the Cat class is created using the new keyword and stored in the variable $ob. This object can now access both the eat() and meow() methods of the Cat class. Finally, the code calls both methods on the object $ob. First, it calls $ob->eat(), which outputs "The animal is eating". Then, it calls $ob->meow(), which outputs "The cat is meowing".

Overall, this code demonstrates how classes can be used to organize related functions and how inheritance can be used to create subclasses with additional functionality.

PHP OOP: polymorphism

A key idea in object-oriented programming is polymorphism, which describes an object's capacity to adopt various forms or exhibit various behaviors depending on the situation in which it is used.

When a class inherits from another class, it has the option to replace the parent class's implementations of certain methods with alternative ones that may behave differently. Due to their additional functionality or unique behaviors, objects of the subclass can be used in the same manner as those of the parent class. As an example:

PHP Code
<?php
   interface Animal {
      public function spk();
   }

   class Cat implements Animal {
      public function spk() {
         echo "Meow!";
      }
   }

   class Dog implements Animal {
      public function spk() {
         echo "Woof!";
      }
   }

   function animalSound(Animal $animal) {
      $animal->spk();
   }

   $obc = new Cat();
   $obd = new Dog();

   echo "<p>Cat: ", animalSound($obc), "</p>";
   echo "<p>Dog: ", animalSound($obd), "</p>";
?>
Output
Cat: Meow!

Dog: Woof!

This PHP code defines an interface Animal with a single method spk(), and two classes Cat and Dog that implement this interface and provide their own implementation for the spk() method. The code also defines a function animalSound() that takes an object of the Animal interface as a parameter and calls its spk() method. The code then creates Cat and Dog objects and passes them to the animalSound() function. Each object's spk() method is called, and the result is echoed to the screen.

PHP OOP: abstract class

An abstract class in PHP is a class that cannot be directly instantiated but can be used as a base class for other classes. Abstract classes are useful for defining a common interface for a group of related classes as well as providing some basic implementation that all subclasses can share. As an example:

PHP Code
<?php
   abstract class Animal {
      protected $name;

      public function __construct($name) {
         $this->name = $name;
      }

      abstract public function spk();
   }

   class Cat extends Animal {
      public function spk() {
         echo "<p>", $this->name . ": Meow!</p>";
      }
   }

   class Dog extends Animal {
      public function spk() {
         echo "<p>", $this->name . ": Woof!</p>";
      }
   }

   $obc = new Cat("Cat");
   $obc->spk();

   $obd = new Dog("Dog");
   $obd->spk();
?>
Output
Cat: Meow!

Dog: Woof!

This PHP code creates an abstract class Animal with the protected property $name and a constructor that sets it. The class also defines an abstract method spk(), which is not implemented. Then, the code defines two classes that extend the Animal class: Cat and Dog. Both of these classes implement the spk() method and define their own implementation of the method. The Cat class implementation of the spk() method outputs the sound a cat makes "Meow!" and the Dog class implementation outputs the sound a dog makes "Woof!".

As a final step, the code creates an instance of the Cat class, gives it the name "Cat," and invokes the spk() method. After that, it instantiates a new Dog object and assigns the name "Dog" to it before invoking the spk() method.

PHP OOP: interface

An interface in PHP is a blueprint for a collection of related methods that a class must implement. Interfaces allow you to define a shared set of behaviors for multiple classes without specifying how those behaviors should be implemented. As an example:

PHP Code
<?php
   interface Animal {
      public function e();
      public function s();
   }

   class Cat implements Animal {
      public function e() {
        echo "<p>The cat is eating.</p>";
      }
      public function s() {
        echo "<p>The cat is sleeping.</p>";
      }
   }

   class Dog implements Animal {
      public function e() {
        echo "<p>The dog is eating.</p>";
      }
      public function s() {
        echo "<p>The dog is sleeping.</p>";
      }
   }

   $obc = new Cat();
   $obc->e();
   $obc->s();

   $obd = new Dog();
   $obd->e();
   $obd->s();
?>
Output
The cat is eating.

The cat is sleeping.

The dog is eating.

The dog is sleeping.

This PHP code defines an interface Animal with two methods e() and s(). Two classes, Cat and Dog, implement this interface and provide their own implementation for the e() and s() methods. The e() method of the Cat class returns "The cat is eating." and the s() method returns "The cat is sleeping." Similarly, the e() method in the Dog class returns "The dog is eating." and the s() method returns "The dog is sleeping."

Two objects are created, one of type Cat and another of type Dog. The e() and s() methods are called on both objects, and the expected output is produced based on the implementation in each class.

This code demonstrates how interfaces can be used to define a set of methods that multiple classes can implement, allowing them to share common behaviors while maintaining their own unique implementations. By using an interface, we can ensure that any class that implements the Animal interface will have the e() and s() methods, making it easier to write reusable code that works with different types of animals.

PHP OOP: trait

A trait in PHP is a mechanism that enables programmers to reuse code across numerous classes without inheriting it. Although a trait cannot be instantiated on its own, it is similar to a class in that it defines methods. Traits are intended to be used as a means of giving other classes extra functionality. As an example, consider the following code fragment:

trait Message {
   public function printMsg() {
      echo "Hello!";
   }
}

"Hello, there!" is printed using the printMsg() method defined by this trait. Adding the "use" keyword to your class declaration is all that's required to make use of this trait. As an example:

PHP Code
<?php
   trait Message {
      public function printMsg() {
         echo "Hello, there!";
      }
   }
   
   class MyClass {
      use Message;
   }

   $ob = new MyClass();
   $ob->printMsg();
?>
Output
Hello, there!

The "MyClass" class uses the "Message" trait to add the printMsg() method to its functionality. Now, whenever an object of the "MyClass" class is created, it will have access to the printMsg() method defined in the "Message" trait.

PHP OOP: encapsulation

Encapsulation is an object-oriented programming principle in PHP that involves restricting access to an object's properties and methods from outside the object. Encapsulation allows objects to conceal their internal state and behavior while only exposing a public interface through which other objects can interact. This helps to prevent accidental changes to an object's state from outside the object and maintains the object's integrity. As an example:

PHP Code
<?php
   class MyCar {
      private $carMake;

      public function __construct($make) {
         $this->carMake = $make;
      }

      public function getCarMake() {
         return $this->carMake;
      }

      public function setCarMake($make) {
         $this->carMake = $make;
      }
   }
   
   $obc = new MyCar("Toyota");
   $obc->setCarMake("Ford");
   echo $obc->getCarMake();
?>
Output
Ford

This PHP code defines a class MyCar with a private property $carMake, a constructor method that initializes the $carMake property with the value passed as an argument, and two public methods getCarMake() and setCarMake() that allow accessing and modifying the $carMake property, respectively. The program then produces a Toyota-specific MyCar object, $obc, of class MyCar. Setting the car's manufacturer to "Ford" involves invoking the $obc object's setCarMake() method with the string "Ford" as the argument. At last, the $obc object's getCarMake() method is invoked to retrieve the vehicle's manufacturer, and this information is then echoed to the output.

The output of the code will be "Ford", which is the value of the $carMake property after it was set to "Ford" using the setCarMake() method and retrieved using the getCarMake() method.

This code adheres to the encapsulation principle, a crucial idea in object-oriented programming. The $carMake property is made private so that only members of the class can access it. Instead, access to the property can be restricted using the public getter and setter methods getCarMake() and setCarMake(). In addition to offering a controlled interface for accessing and changing the property, this enables the class to maintain its internal state.

PHP Online Test


« Previous Tutorial Next Tutorial »


Liked this post? Share it!