PHP Part 8: Object-Oriented Programming In PHP (Classes a Objects)

PHP Part 8: Object-Oriented Programming In PHP (Classes And Objects)


Please Subscribe Youtube| Like Facebook | Follow Twitter

Object-Oriented Programming In PHP

In this article, we will provide a detailed overview of Object-Oriented Programming In PHP (Classes and Objects) and provide examples of how they are used in PHP programming.

Object-Oriented Programming (OOP) is a fundamental paradigm in software development that enables modular, reusable, and efficient code. In this article, we explore key concepts of OOP in PHP with explanations and examples.

The Pillars of Object-Oriented Programming

OOP is built upon four key pillars: encapsulation, inheritance, polymorphism, and abstraction.

Encapsulation

Encapsulation is a fundamental principle of OOP that promotes code organization and data integrity. Additionally, encapsulation allows us to bundle data and related methods within a class, thereby hiding internal details and providing controlled access to the object’s state. Furthermore, by utilizing access modifiers such as public, private, and protected, we can effectively control the visibility of class members and enhance code modularity..

Inheritance

In object-oriented programming (OOP), developers can create new classes based on existing ones through the powerful feature of inheritance. Furthermore, inheritance promotes code reuse and establishes relationships between classes. In this discussion, we will explore the process of creating derived classes, often referred to as child classes, which actively inherit properties and methods from base classes, also known as parent classes. By actively leveraging inheritance, developers can avoid code duplication effectively and enhance existing functionality to actively develop more specialized classes.

Polymorphism

Polymorphism is a crucial aspect of OOP that allows objects of different types to be treated interchangeably. Moreover, polymorphism enhances code flexibility and extensibility. In this discussion, we will focus on method overriding, which enables a derived class to provide its own implementation of a method inherited from a base class.

Abstraction

In OOP, programmers actively utilize abstraction as a powerful tool that simplifies complex systems by focusing on essential features and actively hiding unnecessary details. Through abstraction, programmers can actively create abstract representations of real-world entities or concepts using abstract classes and interfaces. By actively abstracting away specific implementation details, we can actively achieve code modularity, reusability, and organization.

We will explain them further in detail in next article. In this article we will explain Classes and Objects

Classes and Objects

In PHP, a class is a blueprint or template that defines the structure and behavior of an object. It encapsulates data (properties) and functions (methods) into a single entity, allowing you to create multiple instances (objects) based on the class.

An object, on the other hand, is an instance of a class. It represents a specific entity or concept and has its own unique set of properties and behavior.

Creating a Class

To create a class in PHP, you use the class keyword followed by the name of the class. It is recommended to follow proper naming conventions, such as using Pascal Case (e.g., MyClass) and using a descriptive name that reflects the purpose of the class.

class MyClass {
    // properties and methods
}

Defining Properties and Methods

Properties are variables that hold data associated with an object, while methods are functions that define the behavior of an object. You can define properties and methods within a class.

class MyClass {
    // properties
    public $name;
    private $age;

    // methods
    public function sayHello() {
        echo "Hello, I am ".$this->name;
    }

    private function calculateAge() {
        // perform age calculation
    }
}

In the above example, $name is a public property accessible from outside the class, while $age is a private property accessible only within the class. Similarly, sayHello() is a public method, and calculateAge() is a private method.

Creating Objects

To create an object from a class, you use the new keyword followed by the class name and parentheses.

$object = new MyClass();

Once the object is created, you can access its properties and methods using the object operator (->).

$object->name = "John Doe";
$object->sayHello();

Class Constructors and Destructors

Constructors and destructors are special methods in a class that are automatically executed when an object is created and destroyed, respectively.

class MyClass {
    public function __construct() {
        // constructor code here
    }

    public function __destruct() {
        // destructor code here
    }
}

The constructor method is useful for initializing object properties or performing any necessary setup tasks, while the destructor method can be used to clean up resources or perform final operations before the object is destroyed.

In PHP, constructors can be categorized into two main types: no-argument constructors and parameterized constructors.

No-Argument/Non-Parameterized Constructors

A no-argument constructor, also known as a default constructor, is a constructor that does not take any arguments. It is automatically called when an object is created from a class. The purpose of a no-argument constructor is to provide a default state or initialize properties with default values.

In PHP, a no-argument constructor is defined using the __construct() method.

class MyClass {
    public function __construct() {
        // Constructor code here
    }
}

When an object is created from this class, the __construct() method will be automatically invoked, allowing you to perform any necessary initialization tasks.

Parameterized Constructors

Unlike no-argument constructors, parameterized constructors accept one or more arguments. They allow you to pass values to the constructor when creating an object. This enables you to initialize object properties with specific values based on the arguments provided.

To define a parameterized constructor in PHP, you simply add the required parameters to the __construct() method.

class MyClass {
    public function __construct($arg1, $arg2) {
        // Constructor code here
    }
}

When creating an object from this class, you need to provide the corresponding arguments.

$object = new MyClass($value1, $value2);

The constructor will receive these values and you can use them to initialize the object’s properties accordingly.

PHP does not support constructor overloading in the same way as some other programming languages. Constructor overloading refers to having multiple constructors with different parameter lists within a class. However, you can simulate constructor overloading using optional arguments or method overloading techniques.

Example

<?php

class MyClass {
    private $name;
    private $age;

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

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

    public function setAge($age) {
        $this->age = $age;
    }

    public function getName() {
        return $this->name;
    }

    public function getAge() {
        return $this->age;
    }

    public function sayHello() {
        echo "Hello, my name is " . $this->name . " and I am " . $this->age . " years old.";
    }
}

// Create an object of MyClass
$object = new MyClass("Ibrahim", 25);

// Access object properties and call methods
echo $object->getName(); // Output: Ibrahim
echo "<br>";
echo $object->getAge(); // Output: 25
echo "<br>";
$object->setName("Ibrahim");
$object->setAge(30);

$object->sayHello(); // Output: Hello, my name is Ibrahim and I am 30 years old.

?>

Output

Ibrahim
25
Hello, my name is Ibrahim and I am 30 years old.

In the above example, we have a class called MyClass with private variables $name and $age. The constructor __construct() is used to initialize these variables with values passed as arguments when creating an object.

The class also includes setter and getter methods (setName(), setAge(), getName(), and getAge()) to modify and retrieve the values of the variables.

Finally, the sayHello() method is used to display a message with the object’s name and age.

Creating an object of the MyClass and invoking its methods allows you to set and retrieve the values of the object’s variables and execute actions using its methods

this keyword

this keyword in PHP is a reference to the current instance of a class. It allows you to access the properties and methods of the object within its own context. By using $this, you can distinguish between the object’s properties and local variables within a method or constructor. It ensures that the correct instance’s data is accessed and manipulated.

In the provided example, the this keyword is used to refer to the specific instance of the MyClass object being worked with. Inside the class methods, such as setName(), setAge(), getName(), and getAge(), $this->name and $this->age are used to access and modify the object’s own properties ($name and $age).

Static Function And Non-Static Function in PHP

Static functions and non-static functions are two types of methods in PHP classes.

Non-Static Functions (Instance Methods)

Non-static functions, also known as instance methods, are associated with specific instances of a class. They can access and manipulate the object’s properties and perform operations unique to each instance.

To define a non-static function, you declare the function within the class without using the static keyword. Object instances are used to access these functions and interact with specific object data.

Example:

class MyClass {
public $name;

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

public function getName() {
    return $this->name;
}

}

$object = new MyClass();
$object->setName("John Doe");
echo $object->getName(); // Output: John Doe

Output

John Doe

In the example, the setName() and getName() methods are non-static functions. They can be accessed using the $object instance, allowing you to set and retrieve the name property specific to that object.

Static Functions (Class Methods)

Static functions, also called class methods, belong to the class itself rather than individual instances. They are shared among all objects of the class and can be called without creating an object instance.

To define a static function, you use the static keyword before the function declaration. These functions are accessed using the class name, followed by the :: (double colon) operator.

Example:

class MathUtils {
public static function add($num1, $num2) {
return $num1 + $num2;
}
}

echo MathUtils::add(5, 3); // Output: 8

Output

8

In the above code, the add() method is a static function within the MathUtils class. You can directly call it using the class name MathUtils and the :: operator, without creating an object of the class.

Static functions are useful for utility methods, helper functions, or operations that don’t require specific object state or access to instance variables.

Note: Static functions cannot access non-static properties or methods directly, as they do not belong to a specific instance. To access instance-specific properties or methods within a static function, you would need to create an object and use it to access those non-static elements.

Differences between static and non-static functions.

TermStatic Functions (Class Methods)Non-Static Functions (Instance Methods)
DefinitionDefined with static keywordDefined without static keyword
AccessAccessed using the class name and :: operatorAccessed through object instances
Object DependencyNo object instance is requiredRequires an object instance to be called
Object-specific DataCannot access non-static properties or methodsCan access and modify object-specific data
Shared FunctionalityShared among all instances of the classSpecific to each instance of the class
UsageUtility methods, helper functions, shared logicInstance-specific behavior, data manipulation

Conclusion

In conclusion, classes and objects play a vital role in PHP’s object-oriented programming paradigm. They empower developers to create reusable, modular, and easily maintainable code by encapsulating data and behavior into cohesive entities. By understanding how to define classes, create objects, and manipulate properties and methods, developers can fully leverage the power of object-oriented programming in PHP. With a solid grasp of these concepts, developers become well-equipped to build robust and scalable applications.

PHP Beginner Tutorial Series

Please Subscribe Youtube| Like Facebook | Follow Twitter


Leave a Reply

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