PHP – Object Oriented Programming

What is PHP ?

PHP (Hypertext Preprocessor) is a general-purpose programming language that is especially suited for web development. It was originally created by Rasmus Lerdorf in 1994, and it has been in widespread use since the mid-1990s. PHP is a server-side language, which means that it is executed on the server rather than in the user’s browser. This allows PHP to be used to create dynamic web pages that can interact with databases, process form input, and perform other tasks that are not possible with HTML alone.

What is Object Oriented Programming

Object-oriented programming (OOP) is a programming paradigm that is based on the concept of “objects”, which can contain data and code that operates on that data. In OOP, a programmer defines the data type of a data structure, and the kinds of operations (functions) that can be applied to the data structure. This helps to keep related data and functions together, and it makes it easier to reuse code and design scalable systems.

In OOP, objects are created from templates called “classes”. A class defines the properties and behaviors of objects created from it. For example, you might define a “Dog” class that has properties like breed, color, and name, and behaviors like barking, wagging its tail, and fetching a ball. Then you could create individual dog objects based on the “Dog” class, each with its own unique values for those properties and behaviors.

Some of the key benefits of OOP include encapsulation (hiding the implementation details of a class from other parts of the program), inheritance (allowing one class to inherit properties and behaviors from another class), and polymorphism (allowing a single interface to be used with multiple implementations).

Object Oriented Programming with PHP

Object-oriented programming (OOP) is a programming paradigm that is based on the concept of “objects”, which can contain data and code that manipulate that data. In PHP, you can use OOP features to create classes, which are templates for objects, and objects, which are instances of classes.

Syntax for create a PHP Class

<?php 

    class Dog{

}

?>

Example 01

Here is an example of a simple class in PHP:

class Dog {
  // Properties
  public $name;
  public $breed;

  // Methods
  public function bark() {
    echo "Woof!";
  }
}

This class has two properties: $name and $breed, and one method: bark().

To create an object from this class, you can use the new operator:

$dog1 = new Dog;
$dog1->name = "Fido";
$dog1->breed = "Labrador";

Now you have an object called $dog1 that represents a dog with a name of “Fido” and a breed of “Labrador”. You can access the properties of the object using the arrow operator (->), and you can call its methods using parentheses (()). For example:

echo $dog1->name;  // Outputs "Fido"
$dog1->bark();  // Outputs "Woof!"

OOP in PHP also allows you to create constructors, which are special methods that are called when an object is created, and destructors, which are special methods that are called when an object is destroyed. You can also use inheritance to create a class that is a subclass of another class, and polymorphism to create multiple classes with the same method names but different behavior.

Some General Rules for Defining Classes in PHP

  1. A class definition starts with the ‘class’ keyword, followed by the name of the class. The class name should be written in CamelCase, with the first letter of each word capitalized.
  2. The class definition is contained within curly braces (‘{ }‘).
  3. Properties are defined within the class definition as variables. They should be declared with one of the visibility keywords: ‘public’, ‘protected‘, or ‘private’. ‘Public’ properties can be accessed from anywhere, ‘protected’ properties can only be accessed from within the class and its subclasses, and ‘private’ properties can only be accessed from within the class.
  4. Methods are defined within the class definition as functions. They should also be declared with one of the visibility keywords.
  5. The class definition should end with a semicolon (;).

Here is another example of a class in PHP that demonstrates some additional OOP features

Example 02

class Car {
  // Properties
  public $make;
  public $model;
  public $year;
  public $color;
  public $engineSize;

  // Constructor
  public function __construct($make, $model, $year, $color, $engineSize) {
    $this->make = $make;
    $this->model = $model;
    $this->year = $year;
    $this->color = $color;
    $this->engineSize = $engineSize;
  }

  // Method
  public function startEngine() {
    return "Vroom!";
  }
}

// Create an object from the Car class
$car1 = new Car("Ford", "Mustang", 2020, "red", 3.7);

// Access the object's properties
echo $car1->make . "\n";  // Outputs "Ford"
echo $car1->model . "\n";  // Outputs "Mustang"
echo $car1->year . "\n";  // Outputs 2020
echo $car1->color . "\n";  // Outputs "red"
echo $car1->engineSize . "\n";  // Outputs 3.7

// Call the object's method
echo $car1->startEngine();  // Outputs "Vroom!"

This class has a constructor, which is a special method that is called when an object is created. The constructor takes five arguments: $make, $model, $year, $color, and $engineSize, and sets the corresponding properties of the object.

The class also has a method called startEngine(), which returns the string “Vroom!”.

To create an object from this class, you can use the new operator and pass the required arguments to the constructor. In this example, the object $car1 is created with the make “Ford”, model “Mustang”, year 2020, color “red”, and engine size 3.7. You can then access the object’s properties and call its methods as shown.

Create an object from the Car class (using Example 02)

// Create an object from the Car class
$car1 = new Car("Ford", "Mustang", 2020, "red", 3.7);

Access the object’s properties of Class called Car (using Example 02)

// Access the object's properties
echo $car1->make . "\n";  // Outputs "Ford"
echo $car1->model . "\n";  // Outputs "Mustang"
echo $car1->year . "\n";  // Outputs 2020
echo $car1->color . "\n";  // Outputs "red"
echo $car1->engineSize . "\n";  // Outputs 3.7

Call the object’s method (using Example 02)

// Call the object's method
echo $car1->startEngine();  // Outputs "Vroom!"

Here is another example

Example 03

Here is an example of how you can add more methods to the Student class

class Student {
  // Properties
  public $name;
  public $age;
  public $grade;

  // Constructor
  public function __construct($name, $age, $grade) {
    $this->name = $name;
    $this->age = $age;
    $this->grade = $grade;
  }

  // Method to calculate and return the GPA
  public function getGPA() {
    // Calculate and return the GPA
  }

  // Method to enroll the student in a course
  public function enroll($course) {
    // Enroll the student in the course
  }

  // Method to withdraw the student from a course
  public function withdraw($course) {
    // Withdraw the student from the course
  }
}

This Student class now has three additional methods: enroll(), withdraw(), and getGPA(). The enroll() method can be used to enroll the student in a course, and the withdraw() method can be used to withdraw the student from a course. The getGPA() method can be used to calculate and return the student’s GPA.

You can call these methods on an object of the Student class using the arrow operator (->) and parentheses (()). For example:

$student1->enroll("Math 101");  // Enroll the student in Math 101
$student1->withdraw("English 201");  // Withdraw the student from English 201
echo $student1->getGPA();  // Output the student's GPA

For more understanding check this questions and answers

    1. What is a class in PHP?

    A class in PHP is a blueprint for an object. It defines the properties and methods that the object will have.

    2. How do you create an object from a class in PHP?

    To create an object from a class in PHP, you can use the new operator and assign the result to a variable. For example:

      $dog1 = new Dog;
      

      This creates an object from the Dog class and assigns it to the variable $dog1.

      3. How do you access the properties of an object in PHP?

      To access the properties of an object in PHP, you can use the arrow operator (->). For example:

      $dog1->name = "Fido";
      echo $dog1->name;  // Outputs "Fido"
      
      4. How do you call the methods of an object in PHP?

      To call the methods of an object in PHP, you can use the arrow operator (->) followed by the method name and parentheses (()). For example:

      $dog1->bark();  // Outputs "Woof!"
      
      5. Can you create multiple objects from the same class in PHP?

      Yes, you can create multiple objects from the same class in PHP. Each object will have its own set of properties and methods, which can be accessed and called independently.

      Leave a Reply

      Your email address will not be published. Required fields are marked *