Basic concepts of OOPs are as follows:-
- Class
- Object
- Polymorphism
- Inheritance
- Encapsulation
- Abstraction
Encapsulation: Bundling data (attributes) and methods (functions) that operate on the data into a single unit or class. It also involves restricting direct access to some of an object's components.
Inheritance: A mechanism where a new class inherits properties and behaviors (methods) from an existing class. The existing class is called the parent or base class, and the new class is called the child or derived class.
Polymorphism: The ability of different classes to be treated as instances of the same class through inheritance. It also allows methods to have the same name but behave differently based on the object calling them.
Abstraction: The concept of hiding the complex implementation details and showing only the necessary features of an object. It helps in reducing complexity by focusing on the essential characteristics rather than the specific implementation.
A class is a blueprint for creating objects. It defines the properties and methods that the objects created from the class will have.
A class can be understood as a template or a blueprint, which contains some values, known as member data or member, and some set of rules, known as behaviors or functions. So when an object is created, it automatically takes the data and functions that are defined in the class.
-
Class is a programmer-defined data type, which includes local methods and local variables.
Class is a collection of objects. Object has properties and behaviour.
-
First we have to define a php class, where classname should be same as filename.
An object is an instance of a class. It represents a specific entity that has the attributes and behaviors defined by its class.
An object is an instance of a class. To create an object, you use the new keyword followed by the class name, optionally passing any required parameters to the class constructor.
$myObject = new MyClass();
Class-
1. Class is a blueprint of an object.
2. A class can’t instantiate.
4. Class is generic.
Object-
1. An object is an instance of a class.
2. An object can instantiate.
4. Object is specific.
The encapsulation is part of an object and describes all data. Hidden data is restricted to members of this class. Classes are public, private, protected, internal, and internally protected.
Encapsulation can also be defined in two different ways:
1) Data hiding: Encapsulation is the process of hiding unwanted information, such as restricting access to any member of an object.
2) Data binding: Encapsulation is the process of binding the data members and the methods together as a whole, as a class
Polymorphism is nothing more than assigning behavior or value in a subclass to something that has already been declared in the main class. Polymorphism simply takes on more than one form.
Polymorphism - Same operation may be behave differently in different class.
Inheritance is an important concept of OOP (Object Oriented Programming). It is a mechanism in PHP by which the subclass inherits all the properties of the super class.
Inheritance allows a new class (child class) to inherit properties and methods from an existing class (parent class).
For example:
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
pass
class Dog(Animal):
def speak(self):
return f"{self.name} says Woof!"
dog = Dog("Buddy")
print(dog.speak()) # Output: Buddy says Woof!
In this example, the Dog
class inherits from the Animal
class. The Dog
class overrides the speak
method of the Animal
class.
Types of Inheritance:-
- Single Inheritance
- Multilevel Inheritance
- Hierarchical Inheritance
- Hybrid Inheritance
Classes do not consume any memory. They are just a blueprint based on which objects are created. Now when objects are created, they actually initialize the class members and methods and therefore consume memory.
The concepts of class and interface are fundamental in object-oriented programming (OOP), but they serve different purposes. Below are the key differences between them:
1. Definition and Purpose
Class:
- A class is a blueprint for creating objects. It defines the properties (attributes) and behaviors (methods) that the objects instantiated from the class will have.
- A class can provide a full implementation of methods, and it can also maintain state through its instance variables.
class Car {
public $make;
public $model;
public function drive() {
echo "The car is driving";
}
}Interface:
- An interface is a contract that defines a set of methods that implementing classes must provide. It does not contain any implementation itself—only method signatures.
- An interface cannot maintain state because it does not have instance variables.
interface Drivable {
public function drive();
}
2. Implementation
Class:
- A class can provide implementations for all its methods.
- Classes can be instantiated (objects can be created from them).
- A class can inherit from another class using the
extends
keyword (single inheritance).
Interface:
- An interface only provides the method signatures (without the body). The implementing class must provide the actual implementation.
- Interfaces cannot be instantiated directly.
- A class can implement multiple interfaces using the
implements
keyword.
Class:
- PHP supports single inheritance, meaning a class can inherit from only one other class.
- A class can extend another class to inherit its methods and properties.
Interface:
- PHP supports multiple inheritance through interfaces, meaning a class can implement multiple interfaces.
- Interfaces can also extend other interfaces, allowing for more complex contract hierarchies.
3. Inheritance and Multiple Inheritance
Class:
- PHP supports single inheritance, meaning a class can inherit from only one other class.
- A class can extend another class to inherit its methods and properties.
Class:
- PHP supports single inheritance, meaning a class can inherit from only one other class.
- A class can extend another class to inherit its methods and properties.
4. Abstract Classes vs. Interfaces
Class:
- An abstract class is a special type of class that cannot be instantiated on its own and may contain both implemented and abstract (unimplemented) methods. A class that extends an abstract class must implement the abstract methods.
Interface:
- All methods in an interface are abstract by default (i.e., they only define signatures, with no body), and any class implementing the interface must provide the implementation for all its methods.
Summary:
- Classes define the attributes and behaviors of objects, can be instantiated, and may provide full or partial method implementations.
- Interfaces define a contract for what methods a class must implement, without providing any implementation themselves. They allow for multiple inheritance in a way that classes do not.
Method overloading is a feature that allows a class to have more than one method with the same name, but with different parameters (different type, number, or both). It helps in defining multiple behaviors for the same method name.
class MathOperations {
int add(int a, int b) {
return a + b;
}
double add(double a, double b) {
return a + b;
}
}
Here, the add
method is overloaded with different parameter types
The overloading methods are invoked when interacting with properties or methods that have not been declared or are not visible in the current scope. The rest of this section will use the terms inaccessible properties and inaccessible methods to refer to this combination of declaration and visibility.
Property and Rules of overloading in PHP:
- All overloading methods must be defined as Public.
- After creating the object for a class, we can access a set of entities that are properties or methods not defined within the scope of the class.Such entities are said to be overloaded properties or methods, and the process is called as overloading.
- For working with these overloaded properties or functions, PHP magic methods are used.
- Most of the magic methods will be triggered in object context except __callStatic() method which is used in a static context.
Types of Overloading in PHP: There are two types of overloading in PHP. - Property Overloading
- Method Overloading
Method overriding occurs when a subclass provides a specific implementation for a method that is already defined in its superclass. The method in the subclass should have the same name, return type, and parameters as the method in the parent class.
class Animal {
void sound() {
System.out.println("Animal makes a sound");
}
}
class Dog extends Animal {
@Override
void sound() {
System.out.println("Dog barks");
}
}
Here, the Dog
class overrides the sound
method of the Animal
class.
How to use overloading in PHP?
class MainClass {
public function ShowTitle($parameter1) {
echo “Best Interview Question”;
}
public function ShowTitle($parameter1, $parameter2) {
echo “BestInterviewQuestion.com”;
}
}
$object = new MainClass;
$object->ShowTitle(‘Hello’);
Constructors are special methods whose name is the same as the class name. The constructors serve the special purpose of initializing the objects.
For example, suppose there is a class with the name “MyClass”, then when you instantiate this class, you pass the syntax:
MyClass myClassObject = new MyClass();
Static Binding (also known as Early Binding).
Dynamic Binding (also known as Late Binding).
In static binding, function calls are resolved at compile time by the compiler itself. The binding of all the static and private functions/methods of a class happens at compile time. In dynamic binding, function calls are resolved at run time. Function overriding in OOP is possible due to dynamic/late binding
Zero
We cannot create an instance of an abstract class as it does not have any complete implementation.
An abstract class acts like a template or an empty structure.
Overloading is a compile-time polymorphism feature in which an entity has multiple implementations with the same name. For example, Method overloading and Operator overloading.
Whereas Overriding is a runtime polymorphism feature in which an entity has the same name, but its implementation changes during execution. For example, Method overriding
Data abstraction is an important concept of object-oriented programming that displays only the important information and unnecessary details or implementation from the users. This concept helps in reducing programming complexity and efforts.
Data Abstraction has three levels:
- Physical Level (Lowest level of data abstraction): It tells how the data is stored in memory.
- Logical Level: It has the information that is stored in the database in the form of tables. The relationship among the data entities in relatively simple structures is also stored.
- View Level (Highest level of data abstraction): Only a part of the actual database is visible to the user.
It’s a very important feature in the object-oriented program, it provides visibility of methods or property of a class.
There are 3 types of access modifiers available. these follow below:
1. Private : Accessible only within the class itself.
2. Protected : Accessible within the class and by subclasses.
3. Public : Accessible from anywhere.
Different programming languages implement these access modifiers differently, and some languages (like Python) don't enforce them strictly but use naming conventions to indicate their intended use.
An exception is an abnormal event or error that occurs during the execution of a program, which can disrupt the normal flow of the program.
- Default Constructor:- With no parameters.
- Parametric Constructor:- Create a new instance of a class and also passing arguments simultaneously with Parameters.
- Copy Constructor:-Which forms a new object as a copy of an existing object.
Traits are used to declare methods that can be used in multiple classes.
- Traits are a circuitry for code reuse in single inheritance.
- A Trait is similar to a class, but only intended to group functionality in a fine-grained and consistent way.
- It is impossible to instantiate a Trait but in addition to common inheritance. It is assigned to reduce some limitations of single inheritance to reuse sets of methods freely in several independent classes living in several class hierarchy
Ex : - trait message1 {
public function msg1() {
echo "OOP is fun! ";
}
}
class Welcome {
use message1;
}
$obj = new Welcome();
$obj->msg1();
In PHP, this
is a keyword used within a class to refer to the current instance of the class. It is used to access properties and methods of the current object.
Purpose of this
in PHP:
- Accessing Instance Variables:
this
is used to refer to the properties of the current object. - Calling Instance Methods: It is used to call other methods of the same object.
- Differentiating Between Properties and Parameters: When a method's parameter has the same name as a property,
this
is used to differentiate the property from the parameter.
class Car {
public $make;
public $model;
// Constructor to initialize the object
public function __construct($make, $model) {
$this->make = $make; // 'this' refers to the current object's 'make' property
$this->model = $model; // 'this' refers to the current object's 'model' property
}
// Method to display information
public function displayInfo() {
echo "Make: " . $this->make . ", Model: " . $this->model;
}
}
// Creating an object of the Car class
$myCar = new Car("Toyota", "Corolla");
// Accessing properties and methods using 'this'
$myCar->displayInfo(); // Output: Make: Toyota, Model: Corolla
?>
Key Points:
- Properties: Use
this->property_name
to access the properties of the current object. - Methods: Use
this->method_name()
to call methods within the same class.
Why this
is Important in PHP:
- Clarity: It clarifies that the property or method being accessed belongs to the specific instance of the class.
- Avoiding Conflicts: It helps avoid conflicts between class properties and method parameters with the same name.
- Object Context: It ensures that actions are performed on the correct object instance, especially when dealing with multiple instances of the same class.
Final class: The final class is a class that cannot be extended by other classes. So a Class that is declared with the final keyword doesn’t have child classes. A class can be declared as final by prefixing the final keyword before the Class.
The syntax for defining the final class is given below:
Syntax : final Class className
Final method: A method is considered a final method if it is prefixed with the final keyword. The final methods are the methods that cannot be overridden. So, these methods can’t be overridden in child/subclasses. It increases security by preventing the modification of functions.
The syntax for defining a final method is given below:
Syntax : final function functionName(Parameter1, Parameter2, ...);
PHP does not support multiple inheritance because it causes ambiguity and confuses the compiler. In the other words, if the parent class has the same method name, then the compiler will confuse to decide that the method being called belongs to which class.
Namespace is the way of encapsulating the items to reuse the same name without name conflicts. The “Namespace” keyword is used to declare namespaces. It can contain valid PHP code. It declares the namespace at the top of the file before any other code – with one exception: the declare keyword. You can declare namespace globally but without using any name
- Code Reusability: Used to achieve through inheritance and traits.
- Modularity: Used to achieve by breaking large code into small modules, Modularity reduces complexity.
- Maintainability: Used to maintain code that follows Object-Oriented Programming Concepts.
- Testability: it is easy to test.
- Security: Used to achieve by Encapsulation
- Flexibility: We can make by polymorphism.
- Testability: it is easy to test.
An interface is a reference type in Java (or other languages) that is similar to a class but can only contain abstract methods (before Java 8) and final fields. An interface is used to achieve complete abstraction and multiple inheritance in Java.
- Abstract Class: Can have both abstract and non-abstract methods, can have state (fields), and is meant for partial abstraction.
- Interface: Only abstract methods (in earlier versions) and no state, meant for complete abstraction and providing multiple inheritance.
Inheritance: Represents an "is-a" relationship. It allows a class to inherit properties and methods from another class, which promotes reusability.
Composition: Represents a "has-a" relationship. It allows a class to contain references to other classes, enabling complex behaviors by combining simpler ones.
class Engine {
void start() {
System.out.println("Engine started");
}
}
class Car {
private Engine engine = new Engine();
void startCar() {
engine.start();
System.out.println("Car started");
}
}
Here, Car
has an Engine
, which is an example of composition.
A program is a set of instructions that tells the computer what to do. A process is a program that is currently running. In other words, a program is a static entity, while a process is a dynamic entity.
-
To Share this Link, Choose your plateform
1. What Is Object-Oriented Programming?
An object-oriented programming system and OOPs It is a programming language model organized around objects. Objects are instances of classes used to interact with each other. An application can be of any type, such as a web-based application, a windows-based application, etc. Object-oriented programming is all about the objects and the class. OOPS is short for object-oriented programming system, in which programs are viewed as a collection of states.
Object-Oriented Programming (OOP) is a programming paradigm that uses objects and classes to organize code. It allows for the modeling of real-world entities using objects, which encapsulate data (attributes) and behavior (methods).