Understanding OOP in PHP

Learn via video courses
Topics Covered

Overview

Object-oriented programming (OOP) in PHP PHP OOP can be said as a programming model that is based on the concept of objects, which contain data in the form of attributes or properties, and methods, which are functions that can be performed on the object. PHP is a popular server-side scripting language that supports OOP. In PHP, classes are used to define objects, and objects can be created from classes using the "new" keyword. Encapsulation, inheritance, and polymorphism are key concepts of OOP that are supported in PHP.

What is OOP?

PHP OOP, or Object-Oriented Programming, is a programming paradigm used in PHP where objects are created from classes that contain both data in the form of properties and functions in the form of methods. OOP is based on the concepts of encapsulation, inheritance, and polymorphism. Encapsulation provides data hiding and abstraction, allowing for more secure and flexible code. Inheritance allows for the creation of new classes that can inherit properties and methods from existing classes, saving time and effort in code development.

Object-Oriented Concepts and Principles in PHP

Here are some of the key concepts and principles of PHP OOP:

  • Encapsulation: This is the concept of bundling data and behavior within an object and hiding the details from the outside world. In PHP, this is typically achieved through the use of access modifiers such as public, private, and protected.
  • Inheritance: This is the ability to create new classes from existing ones, inheriting properties and methods. In PHP, inheritance is implemented using the "extends" keyword.
  • Polymorphism: This is the ability to create multiple methods with the same name that behave differently depending on the context. In PHP, polymorphism is typically achieved through the use of interfaces and abstract classes.
  • Abstraction: This is the concept of defining a simplified interface for complex functionality. In PHP, this can be achieved through the use of interfaces, abstract classes, and traits.

What are Classes and Objects?

Classes and objects are key components of PHP OOP. A class is a blueprint or template for creating objects, while an object is an instance of a class.

In PHP, a class is defined using the "class" keyword, followed by the class name and a block of code containing properties (data) and methods (functions). For example:

Explanation

This defines a class called "Car" with a public property called "color" and a public method called "StartEngine".

To create an object from this class, the "new" keyword is used, followed by the class name and parentheses. For example:

This creates a new object called "$myCar" from the "Car" class.

Creating Objects in PHP

Objects in PHP are created using the "new" keyword followed by the name of the class.

Here is an example of creating an object in PHP:

Explanation

In PHP, we can also pass arguments to the constructor of a class when creating an object. The constructor is a special method that is called when an object is created and is used to initialize the object's properties.

Here is an example of creating an object with arguments in PHP:

Explanation

In this example, we define a class called "Person" with a constructor that takes two arguments: "name" and "age". We use the "this" keyword to set the values of the object's properties based on the arguments passed to the constructor.

Calling Member Functions in PHP

In PHP, member functions (also called methods) are functions that are defined within a class and can be called on objects of that class. Here is an example of defining and calling a member function in PHP:

Constructor Functions

In PHP OOP, a constructor function is a special method that is called automatically when an object is created. The constructor function is used to initialize the properties of the object and set its initial state.

To define a constructor function in PHP, you use the "__construct()" method. Here is an example of defining and using a constructor function in PHP:

Explanation

In this example, we define a class called "Person" with two public properties: "name" and "age", and a constructor function called "__construct()" that takes two arguments: "name" and "age". Inside the constructor function, we set the values of the object's properties using the "this" keyword.

Destructor

In PHP OOP, a destructor function is a special method that is automatically called when an object is no longer needed and is about to be destroyed. The destructor function is used to perform cleanup tasks before the object is removed from memory.

To define a destructor function in PHP, you use the "__destruct()" method. Here is an example of defining and using a destructor function in PHP:

Explanation In this example, we define a class called "Person" with two public properties: "name" and "age", a constructor function that initializes the properties, and a destructor function called "__destruct()" that prints a message to the console.

We then create an object of the "Person" class using the constructor function and call the "sayHello()" method to print a message to the console.

Finally, we destroy the object using the "unset()" function, which calls the destructor function and prints a message to the console.

Inheritance

Inheritance IN PHP OOP is an important concept in PHP OOP that allows you to create new classes based on existing classes. In PHP, inheritance is supported by the "extends" keyword, which allows a new class to inherit the properties and methods of an existing class.

To create a class that inherits from an existing class, you define a new class using the "class" keyword and include the name of the class that you want to inherit from using the "extends" keyword. Here's an example:

Explanation In this example, we define a base class called "Animal" with a public property called "name" and a public method called "makeSound()". We then create a new class called "Dog" that extends the "Animal" class using the keyword named "extends" . The "Dog" class which we can see in the above example overrides the "makeSound()" method from the "Animal" class to make the dog bark.

Function Overriding

Function overriding in PHP OOP is a concept in object-oriented programming that allows a subclass to provide a different implementation of a method that is already defined in its parent class. In PHP, function overriding is achieved by defining a method with the same name and parameters in the subclass as the method in the parent class.

Here is an example of function overriding in PHP

In this example, we have a parent class called "Animal" with a method called makeSound(). We then define a subclass called "Dog" that extends the "Animal" class using the keyword extends and then it overrides the makeSound() method with a different implementation.

When we create an object of the "Dog" class and call the makeSound() method on it, the subclass implementation of the method is executed instead of the parent class implementation. Run the above code in your editor for a better explanation.

function-overriding

Public Members

In PHP, public members are properties or methods of a class that can be accessed from outside the class. This means that any code that has access to an instance of the class can read or modify the public members.

To define a public member in PHP, you simply declare it using the "public" keyword. Here is an example of a class with public members:

Explanation In this example, we define a class called "Person" with two public properties: "name" and "age", and a public method called sayHello(). The sayHello() method uses the "this" keyword to access the object's properties and prints a message to the console.

Private members

Private members in PHP OOP are properties and methods that are only accessible within the class in which they are defined. This means that they cannot be accessed or modified from outside the class.

To define a private member in PHP, you use the "private" keyword before the property or method name. Here is an example of defining and using private members in PHP:

Protected members

Protected members in PHP OOP are class members (properties and methods) that can only be accessed within the class itself and its subclasses.

To define a protected member in PHP, you use the "protected" keyword before the member name. Here is an example of defining and using a protected member in PHP:

Explanation In this example, we define a class called "Person" with two protected properties: "name" and "age", and a protected method called getAge(). We then define a subclass called "Employee" that inherits from "Person" and adds a private property called "salary" and a public method called getSalary().

Interfaces

Interface in PHP OOP is a collection of abstract methods that define a set of behaviors that a class should implement. An interface provides a blueprint for classes to follow, allowing for greater code flexibility and reusability. Here is an example of defining and using an interface in PHP:

Explanation In this example, we define an interface called "Shape" with two abstract methods: getArea() and getPerimeter(). We then define two classes, Circle and "Rectangle", that implement the "Shape" interface and provide their own implementations of the getArea() and getPerimeter() methods.

Constants

In PHP, a constant is a value that cannot be changed during the execution of a script. Constants are useful when you need to define a value that will be used throughout your code but should not be changed.

To define a constant in PHP, you use the "define()" function, which takes two arguments: the name of the constant and its value. Here is an example of defining and using a constant in PHP:

Explanation In this example, we define a constant called "PI" with a value of 3.14159 using the define() function. We then use the constant in a calculation to calculate the area of a circle with a radius of 5. Finally, we print the result to the console.

Abstract Classes

In PHP, an abstract class is a class that cannot be instantiated directly, but instead must be extended by a subclass. An abstract class serves as a template for other classes to inherit from, providing common functionality that can be reused across multiple classes.

To define an abstract class in PHP, you use the "abstract" keyword in the class declaration. Here is an example of defining and using an abstract class in PHP:

Explanation In this example, we define an abstract class called "Shape" with a protected property "color" and an abstract method getArea(). The getArea() method is not implemented in the abstract class, but is instead defined in a subclass.

Static Keyword

In PHP, the "static" keyword is used to declare class properties and methods that can be accessed without creating an object of the class. Instead, they are accessed directly from the class itself.

Here's an example of how to use the "static" keyword in PHP:

Explanation In this example, we define a class called "MyClass" with a static property called "$myProperty" and a static method called "myMethod()". We can access the static property by using the class name followed by the scope resolution operator "::". Similarly, we can call the static method using the same syntax.

Static properties and methods are useful in scenarios where you need to access shared data or functionality across multiple instances of the class. They are also commonly used in utility classes that don't require any state and simply provide a set of functions or constants.

Final Keyword

In PHP, the final keyword is used to restrict the behavior of a class, method, or property. When a class, method, or property is marked as final, it cannot be extended or overridden by any child class.

The final keyword can be applied to a class declaration, a method declaration, or a property declaration. Here are some examples:

1. Final class declaration:

In the above example, the MyClass class is marked as final, which means that no other class can extend it.

2. Final method declaration:

In the above example, the myMethod() method is marked as final, which means that no child class can override it.

3. Final property declaration:

Explanation

In the above example, the $myProperty property is marked as final, which means that no child class can redeclare or modify its value.

The final keyword can be useful in situations where you want to ensure that a certain class, method, or property is not modified or extended in unintended ways. However, it should be used sparingly, as it can limit the flexibility and extensibility of your code.

Calling Parent Constructors

In PHP, you can call a parent class's constructor using the parent::__construct() method. This is useful when you have a child class that needs to perform some additional initialization that builds upon the work of the parent constructor.

Here's an example of how to call a parent constructor from a child class:

Explanation In the above example, the ChildClass extends the ParentClass and calls the parent constructor using parent::__construct(). This ensures that the parent constructor is executed before the child constructor.

Conclusion

  • OOP is a programming paradigm that emphasizes the use of objects to represent real-world entities, rather than just functions and data.
  • In PHP, you can define classes to create objects, which encapsulate both data and functionality.
  • Classes can have properties, which are variables that store object data, and methods, which are functions that perform object actions.
  • Inheritance is a key feature of OOP in PHP, which allows child classes to inherit properties and methods from parent classes.