Object-Oriented Programming in PHP

In Object-Oriented Programming (OOP), objects are used to design and develop applications. It is widely used for creating dynamic websites, developing large-scale software systems, and creating reusable components. To build better, scalable, and maintainable applications, this article will provide an overview of OOP in PHP.

  • It organizes and manipulates data using classes, objects, and methods.
  • An object is a class instance.
  • A class has methods and attributes that define the actions of the object.
  • We use a new operator to create an object after creating a class.

What are CLASS and OBJECTS in PHP OOP?

In PHP, classes serve as an object creation blueprint. A class may have methods/functions and properties/variables. Using the new keyword, objects are created as instances of classes.

Data is stored by properties of an object and a method operate on data.

Class keywords are used to define classes, followed by their names.

Class definitions contain curly braces that define a class’s properties and methods.

Below are the example of a class definition in PHP

class Members {
	public $member;
	public $member_email;

	public function __construct($member, $member_email){
		$this-> member = $member;
		$this-> member_email = $member_email;
	}

	public function getMembername() {
		return $this->member;
	}

	public function getMemberEmail(){
		return $this->member_email;
	}
}
$member = new Members("Rahul", "[email protected]");
  • The code above is creating a class called Members.
  • The class has two properties, member and member_email.
  • The constructor function is used to initialize the values of these properties when an object of this class is created.
  • The constructor function takes in two parameters, $member and $member_email which are then assigned to the corresponding properties using the “this” keyword.
  • This allows us to access these properties from within the class.
  • Next, we have two methods defined within the class – getMembername() and getMemberEmail().
  • These methods simply return the value of their respective properties when called upon.
  • In order to create an instance of this class, we use the “new” keyword followed by the name of our class and pass in arguments for our constructor function if necessary.
  • In this case, we are passing in “Rahul” as a value for $member and “[email protected]” as a value for $member_email.
  • This creates an object named “$member” with its own set of unique property values based on what was passed into it during instantiation.
  • We can now access these values by calling upon our getter methods like so: “$member->getMembername()” or “$member->getMemberEmail()”.
  • Overall, this code demonstrates how classes can be used to create objects with predefined sets of data that can be accessed through various functions or methods defined within them.
  • It also showcases how constructors work in PHP – allowing us to initialize property values at runtime while creating new instances of our classes.
  • The code creates a class called Members with properties for member name and email and methods to retrieve those values.
  • An instance of the class is then created with the name “Rahul” and email “[email protected]”.

CREATING OBJECTS FROM CLASSES.

To create an object from a class, use the new keyword followed by the class name. The following is an example.

$member = new Members("Rahul", "[email protected]");

How we can access the properties and methods of the $member object:

echo $user->member; // Outputs: "Rahul"

echo $user->member_email; // Outputs: "[email protected]"

echo $user->getMembername(); // Outputs: "Rahul"

echo $user->getMemberEmail(); // Outputs: "[email protected]"

Inheritance in PHP OOP

Functions and attributes from parent classes can be inherited by child classes. A new class can be created based on an existing class without having to rewrite all the code. By using the keyword extends, inheritance can be defined.

To create a subclass, we can use the extend keyword with the name of the parent class.

class ChildClass extends ParentClass {
    // Class body
}

  • The code above creates a class called “Head” which extends the “Member” class.
  • This means that the Head class will inherit all of the properties and methods from the Member class, but can also have its unique properties and methods.
  • The first line of code declares that this new Head class is extending (or inheriting from) the Member class.
  • This allows us to reuse any common functionality between these two classes without having to write it out again.
  • Next, we see two public variables being declared – $member_permissions and $member_email.
  • These are both part of the parent-member class, so they do not need to be redefined here.
  • In order for an object (an instance of a class) to be created using this Head template, we need to pass in three arguments: $member, $member_email, and $member_permissions.
  • The constructor function then uses these arguments to set values for each property in our new object.
  • The parent::__construct() call within the constructor function ensures that any necessary initialization tasks defined in the parent Member constructor are also executed when creating a new Head object.
  • Finally, there is a method called getMemberPermissions(), which simply returns the value stored in the member_permissions property.

A subclass can override a parent class’ method using inheritance, which allows them to provide a new implementation.

The subclass must declare a new method with the same name as the overridden parent class method.

class ParentClass {
    public function displayMessage() {
        echo "Hello from ParentClass";
    }
}

class ChildClass extends ParentClass {
    public function displayMessage() {
        echo "Hello from ChildClass";
    }
}
class ChildClass extends ParentClass {
    public function displayMessage() {
        parent::displayMessage();
        echo "Hello from ChildClass";
    }
}

We are using the parent keyword to access the parent class method.

Polymorphism in PHP OOP

The concept of polymorphism describes the ability to treat objects from different classes similar to those from the same class. Polymorphism is the concept of defining common methods in parent classes and implementing them in child classes.

Below is the code

class Members {
	public $member;
	public $member_email;

	public function __construct($member, $member_email){
		$this-> member = $member;
		$this-> member_email = $member_email;
	}

	public function getMembername() {
		return $this->member;
	}

	public function getMemberEmail(){
		return $this->member_email;
	}
	public function showInfo()
        {
        echo "Membername: " . $this-> member . "\n";
        echo "MemberEmail: " . $this-> member_email . "\n";
    }
}


Class Admin extends Members {
	Public $member_permissions;
	public function __construct($member, $email, $permissions){
		parent::__construct($member, $email);
		$this->member_permissions = $member_permissions;
	}
	public function getPermissions() {
		return $this->member_permissions;
	}

	public function showInfo()
    {
        parent::showInfo();
        echo "MemberPermissions: " . $this->member_permissions . "\n";
    }

 }

$member = new Members("Rahul", "[email protected]");
$admin = new Admin("Simran", "[email protected]", ["write", "delete"]);
$members = [$member, $admin];
foreach ($members as $member) {
    $user->showInfo();
}

  • In this code, we have two classes – Members and Admin.
  • The members class has two properties – member name and member email, while the admin class inherits these properties from the members class and adds another property called member permissions.
  • The __construct() function is a special method that gets executed automatically when an object is created from a class.
  • It takes in parameters that are used to initialize the object’s properties.
  • The parent::__construct() statement inside the admin constructor calls the constructor of the parent (members) class, allowing us to set values for its properties as well.
  • The getMembername() and getMemberEmail() methods are getter functions that allow us to access the private properties of both classes from outside their scope.
  • The showInfo() method prints out all information about each user by accessing their respective properties using $this->property_name syntax.
  • Finally, we create instances (objects) of both classes – $member and $admin – passing in values for their respective parameters.
  • We then store them in an array called $members before looping through it using foreach loop to call each user’s showInfo() method
  • The code creates a class for members and admin, with the admin class inheriting from the members class.
  • It also creates objects for a member and an admin and then displays their information using a loop.

CONSTRUCTORS

  • CONSTRUCTORS are special methods that are automatically invoked when an object is created.
  • As well as initializing the object’s properties, a constructor sets the object’s state.
class Car {
   public function __construct() {
      // constructor code goes here
   }
}
  • In the constructor, we can add the parameters if you want to add the values to the object.
  • The constructor is automatically invoked upon object creation, and any code included within it is run.

PHP Access Modifier

There are three main access modifiers. Public, Protected, Private

Class method visibility and accessibility is managed by access modifiers.

PUBLIC Access Modifier: Any object can access and modify class members and public methods by using the public access modifier.

Protected Access Modifier: This permits objects to access and modify protected class members and methods, whether they are in the same class or any of its child classes.

Private Access Modifier: Private methods and class members can only be accessed and changed by objects that belong to the same class.

Constant In PHP OOP

Constant are the fixed values, they cannot be changed during the execution.

Constants are defined within the class and they can be accessed with the class name.

Using the const keyword Constant is defined, with the constant name and value.

For Example

class AnyClass {

    const CONSTANT = 'value';

    public function showConstant() {

        echo self::CONSTANT . "\n";

    }

}

Constant can be accessed by the class name and double colon operator (::).

Using the self-keyword with the double colon operator, we can access the constant within the class. We can use the class name to access the constant from outside the class.

class Class {

    const CONSTANT = 'constant value';

    public function showConstant() {

        echo self::CONSTANT . "\n";

    }
}

echo Class::CONSTANT . "\n";

$class = new Class();

$class->showConstant();

techfixxo Avatar

Leave a Reply

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