Object oriented programming is a programming technique to design your application. Application can be of any type like it can be web based application, windows based application etc.
In object oriented programming, everything revolves around the objects and class.
A class is a template for an object, a user-defined datatype that contains variables, properties, and methods.
Class represents all properties and behaviors of object.
"; } } //To create php object we have to use a new operator. $obj = new Person("Ajay", 23); echo $obj->getUserDetails(); //Output: Hi, My Name is Ajay and I'm 23 old
Objects are created from Classes, is an instance of a class that is created dynamically.
Object in programming is similar to real word object. Every programming object has some properties and behaviors.
You can create object of class with the help of new keyword
You may also like - Node Js Interview Questions Answers
They look very much same but are not same.
- A class is a definition, while an object is an instance of the class.
- A class is a blueprint while objects are actual objects existing in the real world.
Suppose we have a class Person which has attributes and methods like name, age, height, weight, color etc.
Class Person is just a prototype, now we can create real-time objects of class Person.
#Example: Ajay is real time object of class Person, which have name=Ajay, age=23, height=170cm, weight=60kg and color=black etc.
- A way to bind data and associated functions together.
- Class have many objects.
- Class is a template for creating objects.
- It is logical existence.
- Memory space is not allocated, when it is created.
- Definition (Declaration) is created once.
- Class is declared using "class" keyword.
- Basic runtime entity in object oriented environment.
- Object belongs to only class.
- Object are a implementation of class.
- It is physical existence.
- Memory space is allocated when it is created.
- It is created many times as you required.
- Object is the instance or variable of class.
Constructor is a special type of function which will be called automatically whenever there is any object created from a class.
Note- Old style constructors are DEPRECATED in PHP 7.0, and will be removed in a future version. You should always use __construct() in new code.
Destructor is a special type of function which will be called automatically whenever any object is deleted or goes out of scope.
- Default constructor
- Parameterized constructor
- Copy Constructor
- Static Constructor
- Private Constructor
A constructor without any parameters is called a default constructor.
A constructor with at least one parameter is called a parametrized constructor.
Purpose of Private Constructor: It ensures that there can be only one instance of a Class and provides a global access point to that instance and this is common with The Singleton Pattern.
Member Variable − These are the variables defined inside a class. This data will be invisible to the outside of the class and can be accessed via member functions. These variables are called attribute of the object once an object is created.
Member function − These are the function defined inside a class and are used to access object data.
Each method and property has its visibility. There are three types of visibility in PHP.
- public: Public method or variable can be accessible from anywhere, Means a public method or variable of a class can be called outside of the class or in a subclass.
- protected: A protected method or variable can only be called in that class & it's subclass.
- private: A private method or variable of a class can only be called inside that class only in which it is declared.
NOTE: By default, in PHP, a class member is public unless declared private or protected.
Wrapping up member variables and methods together into a single unit (i.e. Class) is called Encapsulation.
- Encapsulation is used to hide the values or state of a structured data object inside a class, preventing unauthorized parties' direct access to them.
- Visibility is the mechanism for encapsulation.
You may also like - Core PHP Interview Questions Answers
Abstraction is a concept in which implementation details are hidden.
Abstract class are class which contains atleast one or more abstract method.
Abstract method is a method which is declared, but not defined.
- PHP 5 introduces abstract classes and methods.
- Classes defined as abstract may not be instantiated
- Classes that contains at least one abstract method must also be abstract.
- Methods defined as abstract simply declare the method's signature - they cannot define the implementation. Abstract methods cannot be defined as private.
- Classes which are inheriting it's parent class must provides implementations for the abstract methods.
No. there is no need for a class property to be abstract. Class properties and constants are not implemented, instead, they are declared, which in a way already makes them abstract. They follow the same rules and are treated the same way when declared in an abstract class as they would any other class.
Note: All the remaining classes which are not abstract are called Concrete Classes
Suppose we were modeling the behavior of animals, by creating a class hierarchy that started with a base class called Animal.
Animals are capable of doing different things like flying, digging and walking, but there are some common operations as well like eating and sleeping.
Some common operations are performed by all animals, but in a different way as well.
When an operation is performed in a different way, it is a good candidate for an abstract method (forcing subclasses to provide a custom implementation).
It is simply "One thing, can use in different forms". Technically, it is the ability to redefine methods for derived classes.
#Example: One Class (Car) can extend two classes (Audi & BMW).
Polymorphism describes a pattern in object oriented programming in which classes have different functionality while sharing a common interface.
You may also like - MYSQL Interview Questions Answers
Polymorphism could be static and dynamic both. Overloading is static polymorphism while, overriding is dynamic polymorphism.
- Compile time polymorphism (Static) - Method Overloading
- Runtime time polymorphism (Dynamic) - Method Overriding
- Overloading is defining functions/methods that have same signatures with different parameters in the same class.
- Overriding is redefining parent class functions/methods in child class with same signature. So, basically the purpose of overriding is to change the behavior of your parent class method.
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.
An interface is an agreement or a contract. When a class implements an interface, It means it contains same public methods of an interface with their implementation.
In order to implement the polymorphism principle, we can choose between abstract classes and interfaces.
In the example given below, the interface with the name of Shape commits all the classes that implement it to define an abstract method with the name of calcArea().
In accordance, the Circle class implements the interface Shape by putting into the calcArea() method the formula that calculates the area of circles.
The Rectangle class also implements the interface Shape but defines the method calcArea() with a calculation formula that is suitable for rectangles:
Now, we can create objects from the concrete classes:
We can be sure that all of the objects calculate the area with the method that has the name of calcArea(), whether it is a rectangle object or a circle object (or any other shape), as long as they implement the Shape interface.
Now, we can use the calcArea() methods to calculate the area of the shapes:
Note:Polymorphism enhances the flexibility and reusability of the application
Concrete classes are those classes which has to declare body of abstract methods which extends or implements from abstract class or interfaceOR
Abstract classes usually have partial or no implementation. On the other hand, Concrete classes always have full implementation of its behavior. Unlike Concrete classes, Abstract classes cannot be instantiated.
|In abstract class a method must be declared as abstract. Abstract methods doesn’t have any implementation.||In interface all the methods by default are abstract.|
|Abstract class can also contain member variables and concrete functions/methods.||Interfaces cannot contain any member variables and concrete functions/methods except constants.|
|An Abstract methods can be declare with access modifiers like public, protected etc. Concrete Class which is extending the abstract class must be defined with the same or visibility.||All methods declared in an interface must be public.|
|A class can Inherits only one Abstract class and Multiple inheritance is not possible for Abstract class.||A class can implements many interfaces and Multiple interface inheritance is possible.|
|Only complete member of abstract class can be static.||Memebrs of Interface can not be static.|
Abstract Class is used when you something you know (Concrete Methods) and something which you don't know (Abstract Methods).
Interface is used when you don't know anything about implementation. (All methods are abstract)
Consider we are developing a flights booking service.
- Displaying flights available from vendors like "Air India", "IndiGO" and "British Airways" etc
- Place an order for seat to respective vendor.
Remember, In this application, we don't own any flights. we are just a service provider mediator.
So, basically we need two methods:
- checkFlightsAvailability() - to check available flights from all filghts service comapny.
- bookFlights() - to book flights from the availbale flights service company.
So finally, Interface is useful because we are not aware of the actual implementation of all above methods required, we just only know the contract methods that vendor(implementer) should provide.
Note: Properties cannot be declared final, only classes and methods may be declared as final.
Declaring class member variables or methods as static makes them accessible without needing an instantiation of the class. A member declared as static cannot be accessed with an instantiated class object (though a static method can).
- Static Methods and Properties in PHP will be treated as public if no visibility is defined.
- static can also be used to define static variables and for late static bindings.
- In PHP 5, calling non-static methods statically generates an E_STRICT level warning.
- In PHP 7, calling non-static methods statically is deprecated, and will generate an E_DEPRECATED warning. Support for calling non-static methods statically may be removed in the future.
You may also like - MongoDB Interview Questions Answers
Traits are a mechanism for code reuse in single inheritance languages such as PHP.
- A Trait is intended to reduce some limitations of single inheritance by enabling a developer to reuse sets of methods freely in several independent classes living in different class hierarchies.
- The semantics of the combination of Traits and classes is defined in a way which reduces complexity and avoids the typical problems associated with multiple inheritance and Mixins.
- A Trait is similar to a class, but only intended to group functionality in a fine-grained and consistent way.
- It is not possible to instantiate a Trait but an addition to traditional inheritance. It is intended to reduce some limitations of single inheritance to reuse sets of methods freely in several independent classes living in different class hierarchies.
- Multiple Traits can be inserted into a class by listing them in the use statement, separated by commas(,).
- If two Traits insert a method with the same name, a fatal error is produced.
Note: Multiple traits can be used in a class by listing them in the use statement, separated by commas.
If two traits insert a method with the same name, a fatal error is produced, if the conflict is not explicitly resolved. To resolve naming conflicts between traits used in the same class, the insteadof operator needs to be used to choose exactly one of the conflicting methods.
Since this only allows one to exclude methods, the as operator can be used to add an alias to one of the methods. Note the as the operator does not rename the method and it does not affect any other method either.
In this example, Talker uses the traits A and B. Since A and B have conflicting methods, it defines to use the variant of Smalltalk from trait B, and the variant of bigTalk from trait A.
The Aliased_Talker makes use of the as an operator to be able to use B's bigTalk implementation under an additional alias talk.
Type Hinting is used to specify the expected data type (arrays, objects, interface, etc.) for an argument in a function declaration.
It is beneficial because it results in better code organization and improved error messages.
Suppose we want to force a function to get only arguments of the type array, then we can simply put the array keyword before argument's name.
It is also know as Type Declaration.
Namespaces is used to avoid conflicting definitions and enables more flexibility and organization in your code base.
In PHP version 5.3 a new feature was added to the language known as namespace.
In PHP we can’t have two classes that have same name. Name should be be unique. The issue with this restriction is that if you are using any third party library which has a class named User, then you can’t create your own class with name User.
You can import namespaces into anohter namespace or class using the "use" and "as" keywords.
Note: Namespace names are case-insensitive.
- Code Resusability: it can be acheived through inheritance and traits
- Modularity: it can be acheived through breaking large code into small modules, Modularity reduces complexity.
- Flexibility: it can be acheived through polymorphism
- Maintainability: it is to maintian code which follow Object Oriented Programming Concepts.
- Security: it can be acheived through Encapsulation
- Testability: it is easy to test.
This is all about PHP OOPs Interview Questions | OOPs Concepts in PHP