Showing posts with label OOP. Show all posts
Showing posts with label OOP. Show all posts

Wednesday 20 December 2017

Encapsulation in PHP (OOP)

Encapsulation in PHP (OOP)

Question: What is Encapsulation?
The wrapping up of "Data member" and "Member functions" into a single unit (called class) is known as encapsulation.

Question: Describe the Encapsulation?
Encapsulation means hiding the internal details of an object.
Encapsulation is a technique used to protect the information in an object from the other object.

Question: Give Example of the Encapsulation?
class Arithmetic {
    private $first = 10;
    private $second = 50;

    function add() {
        return $this->first + $this->second;

    function multiply() {
        return $this->first * $this->second;


//Create the object 
$obj = new Arithmetic( );

//Add Two number
echo $obj->add(); //60
//multiply Two number
echo $obj->multiply(); //500

Thursday 7 January 2016

OOP Interview Questions and Answers

OOP Interview Questions and Answers

What is Object Oriented Programming?
Object-oriented programming (OOP) is a programming language model organized around objects rather than actions;
Objects are instances of classes, are used to interact with one another.

Following are few examples of object-oriented programming languages
PHP, C++, Objective-C, Smalltalk, C#, Perl, Python, Ruby.

The goals of object-oriented programming are:
  1. Increased understanding.
  2. Ease of maintenance.
  3. Ease of evolution.

What is data modeling?
In class, we create multiple get/set function to get and set the data through the protected functions known as Data Modeling.
class dataModel {    
    public function __set( $key, $value ) {
        $this->$key = $value;
Following are the benefits of Data Modeling
  1. It is very fast.
  2. Smart way to  manipulation on data
  3. No extra layer of logic 
  4. Really flexible to be modeled per need 
  5. Setters can explicitly define what data can be loaded into the object

What is difference between class and interface?
1) Interfaces do not contain business logic
2)You must extend interface to use.
3) You can't create object of interface.

How Session - cookie works in PHP?
When a website open in new client machine(Browser), new sessionId is created and stored in php server and in client machine (In cookie).
All data is store in PHP Server and cookie only have sessionId. When client send sessionId with request to the server, then server fetch the data corresponsing to that sessionId and retun to the browser.

What are some of the big changes PHP has gone through in the past few years?
5.1 added PDO
5.3 - added namespace support

What is Polymorphism?
It is simply "One thing, can use in different forms"
For example, One car (class) can extend two classes (hond & Alta)

How to load classes in PHP.
We can load a class with the use of "autoload" class.
If we want to change from default function autoload to testautload function.
we can do this with "spl_autoload_register"

How to call parent constructor?

Are Parent constructors called implicitly when create an object of class?
No, Parent constructors are not called implicitly It must call this explicitly. But If Child constructors is missing then parent constructor called implicitly.

What happen, If constructor is defined as private OR protected.
If constructor declared as private, PHP through the following fatal error when create object. Fatal error: Call to private BaseClass::__construct() from invalid context in. If constructor declared as private, PHP through the following fatal error when create object. Fatal error: Call to protected BaseClass::__construct() from invalid context in

What happen, If New-Style constructor & old-style constructor are defined. Which one will be called.
New-Style constructor will called. But if New-Style constructor is missing, old style constructor will called.

What are different visibility of method/property?
There are 3 types of visibility of method & property and are following
Public: Can be accessed from same class method, child class and from outside of class.
Protected : Can be accessed from same class method, child class.
Private: Can be accessed from same class method only.
class TestClass
    public $public = 'Public';
    protected $protected = 'Protected';
    private $private = 'Private';

    function printValue()
        echo $this->public;
        echo $this->protected;
        echo $this->private;

$obj = new TestClass();
echo $obj->public; // Works
echo $obj->protected; // Fatal error: Cannot access protected property TestClass::$protected in
echo $obj->private; // Fatal error: Cannot access private property TestClass::$private in C:\wamp\www\arun\class\class.php on line 20
$obj->printValue(); // Shows Public, Protected and Private 

What is Scope Resolution Operator?
The Scope Resolution Operator (also called Paamayim Nekudotayim) is double colon that allows access to static, constant, and overridden properties or methods of a class. Following are different uses Access to static
Acess the constant
Access the overridden properties of parent class
Access the overridden methods of a parent class

What is Static Keyword in PHP?
  • If we declare a Method or Class Property as static, then we can access that without use of instantiation of the class.
  • Static Method are faster than Normal method.
  • $this is not available within Static Method.
  • Static properties cannot be accessed through the object(i.e arrow operator)
  • Calling non-static methods with Scope Resolution operator, generates an E_STRICT level warning.
  • Static properties may only be initialized using a literal or constant value.
  • Static properties/Normal properties Can't be initialized using expressions value.

class StaticClass
    public static $staticValue = 'foo';

    public function staticValue() {
        return self::$my_static;
echo StaticClass::$staticValue;

What is Abstraction in PHP?
  • Abstraction are defined using the keyword abstract .
  • PHP 5 introduces abstract classes and methods. Classes defined as abstract may not be instantiated (create object).
  • To extend the Abstract class, extends operator is used.
  • You can inherit only one abstract class at one time extending.
  • Any class that contains one abstract method must also be declare as abstract. Methods defined as abstract simply declare the method's signature, they can't define the implementation.
  • All methods marked as abstract in the parent's class, declaration must be defined by the child.
  • additionally, these methods must be defined with the same (or a less restricted) visibility (Public,Protected & private).
  • Type hint & number of parameter must be match between parent & child class.

What is Interface in PHP?
  • Interfaces are defined using the interface keyword.
  • All methods declared in an interface must be public. Classes defined as Interface may not be instantiated(create object).
  • To extend the interface class, implements operator is used.
  • You can inherit number of interface class at the time of extending and number of abstract class separated by comma.
  • All methods in the interface must be implemented within a child class; failure to do so will result in a fatal error.
  • Interfaces can be extended like classes using the extends operator.
  • The class implementing the interface must use the exact same method signatures as are defined in the interface. Not doing so will result in a fatal error.
  • Type hint & number of parameter must be match.

What is Traits in PHP?
  1. Traits are a mechanism for code reuse in single inheritance.
  2. A Trait is similar to a class, but only intended to group functionality in a fine-grained and consistent way. 
  3. It is not possible to instantiate a Trait but 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.
  4. Multiple Traits can be inserted into a class by listing them in the use statement, separated by commas(,).
  5. If two Traits insert a method with the same name, a fatal error is produced.

    Example of Traits
class BaseClass{
    function getReturnType() {
        return 'BaseClass';
trait traitSample {
    function getReturnType() {
        echo "TraitSample:";

class Class1 extends BaseClass {
    use traitSample;   

$obj1 = new Class1();

What is Overloading?
It is dynamically create method / properties and performed by magic methods. Overloading method / properties are invoked when interacting with properties or methods that have not been declared or are not visible in the current scope, Means we you are calling a function which is not exist. None of the arguments of these magic methods can be passed by reference.
In PHP, Overloading is possible

What is Object Iteration?
PHP provides a way for objects to be iterate through a list of items, for this we can use foreach. Only visible properties will be listed.
class TestClass{
    public $public='PublicVal';
    protected $protected='ProtectedVal';
    private $private='PrivateVal';
    function myfunc() {
        return 'func';
    function iterateVisible(){
        foreach($this as $key => $value) {
           print "$key => $value\n";

$obj=new TestClass();

What is Final Keyword in PHP?
PHP introduces the final keyword, which prevents child classes from overriding a method by prefixing the definition with final.
If the class itself is being defined final then it cannot be extended. If the function itself is being defined final then it cannot be extended.

What is Serialize function in php?
It return string containing a byte-stream representation of any value that can be stored in PHP.

Comparing Objects?
When using the comparison operator (==), object variables are compared in a simple manner, namely: Two object instances are equal if they have the same attributes and values, and are instances of the same class.
When using the identity operator (===), object variables are identical if and only if they refer to the same instance of the same class

What is UML?
UML stands for Unified Modeling Language.
You can do following things with UML
  • Manage project complexity.
  • create database schema.
  • Produce reports.

What are Properties of Object Oriented Systems?
  • Inheritance
  • Encapsulation of data
  • Extensibility of existing data types and classes
  • Support for complex data types
  • Aggregation
  • Association 

Question: What is serialization?
serialization: returns a string containing a byte-stream representation of any value that can be stored in PHP.
Before starting your serialization process, PHP will execute the __sleep function automatically.

What can you Serialize?
  1. Variables
  2. Arrays
  3. Objects

For example
$str_array = array( "I", "Love", "PHP" );
$serialized_str = serialize($str_array);
echo $serialized_str;

Question: What is un-serialization?
unserialize: can use this string to recreate the original variable values.
Before starting your unserialization process, PHP will execute the __wakeup function automatically.

What can you  un-Serialize?

$unserialized = unserialize('a:3:{i:0;s:1:"I";i:1;s:4:"Love";i:2;s:3:"PHP";}');

Array ( [0] => I [1] => Love [2] => PHP )

Friday 23 October 2015

Object Oriented JavaScript interview questions and answers for experienced

Object Oriented JavaScript interview questions and answers for experienced

Question: Is JavaScript case sensitive?
Yes, JavaScript is a case sensitive..

Question:What are different Data-Types of JavaScript?
Following are different data-type in JavaScript.
  1. String
  2. Number
  3. Boolean
  4. Function
  5. Object
  6. Null
  7. Undefined

Question: What is an Object?
The object is a collection of properties & each property associated with the name-value pairs.
The object can contain any data types (numbers, string, arrays, object etc.).

Question: What are different two ways of creating an object?
Object Literals: This is the most common way to create the object with object literal.
For Example:
var emptyObj= {};

Object Constructor: It is way to create object using object constructor and the constructor is used to initialize new object.
For Example:
Var obj = new Object();

Question: What is scope variable in JavaScript?
The scope is set of objects which can be variables and function.
"Scope variable" can be have global scope variable and local scope variable.

Question: Give an example creating Global variable
Global variable: A variable which can be variable from any where of the page.
Following are different two ways.
First Way Declare the JavaScript variable at the top of JavaScript code and out of function & objects.
var globalVariable1 ='This is global variable 1'

Second WayDeclare a varaible without "var" in Function.
function testfunction(){
    globalVariable2 ='This is global variable 2'

Question: Give an example creating Global variable
Local variable: A variable which can be local and can't access globally.
When we declare a local varriable, Its local and can't access globally. It must create using "var" keyword.
function testfunction1(){
    var localVariable ='This is local variable '

Question: What is public, private and static variables in JavaScript?
Public Varaible: A variable which associate to object and is publicily available with object.
For Example:
function funcName1 (name) {

Private Variable: A variable which associate to object and is limited available.
For Example:
function funcName2 (name) {
 var privateVar='1'; 

Static variable: A static member is shared by all instances of the class as well as the class itself and only stored in one place.
For Example:
function funcName3 (name) {
// Static property = "Web Technology Experts Notes";

Question: How to achieve inheritance in JavaScript
"Pseudo classical inheritance" and "Prototype inheritance"

Question: What is closure in JavaScript?
When we create the JavaScript function within another function and the inner function freely access all the variable of outer function.

Question: What is prototype in JavaScript?
All the JavaScript objects has an object and its property called prototype & it is used to add and the custom functions and property. See Following example in which we create a property and function.
var empInstance = new employee();
empInstance.deportment = "Information Technology";
empInstance.listemployee = function(){


Saturday 20 December 2014

Difference between overloading and overriding in php with Example

Difference between overloading and overriding in php with Example

Overloading: In Real world, overloading means assigning some extra stuff to someone. As as in real world Overloading in PHP means calling extra functions.
Example of Overloading:
class testclass {
    public $_data;
    public function __get($name) {
        echo "Getting '$name'\n ";
        return $this->data[$name];

$obj = new testclass();
/** Magic method Example * */
echo $obj->a; //As __get function called - Overloading example 2
/** Magic method Example * */ 

We can do overloading with magic methods and are following:
__construct(), __destruct(), __call(), __callStatic(), __get(), __set(), __isset(), __unset(), __sleep(), __wakeup(), __toString(), __invoke(), __set_state(), __clone() and __debugInfo()

Overriding: In Real world, Overriding means changing the parental behaviour in Child. As as in real world Overriding in PHP means calling of child function instead of parent function, both class's function have same name.
Example of Overriding:
class parentclass {
    function name() {
        return 'Parent';

class childclass extends parentclass {
    function name() {
        return 'Child';

$obj = new childclass();
echo $obj->name();//It called child function instead of parent parent function - Overriding Example

Sunday 14 December 2014

Object Oriented Programming in PHP

Object Oriented Programming in PHP

Following concept are used in Object Oriented Programming in PHP.

  1. Introduction
  2. The Basics
  3. Properties
  4. Class Constants
  5. Autoloading Classes
  6. Constructors and Destructors
  7. Visibility
  8. Object Inheritance
  9. Scope Resolution Operator (::)
  10. Static Keyword
  11. Class Abstraction
  12. Object Interfaces
  13. Traits
  14. Overloading
  15. Object Iteration
  16. Magic Methods
  17. Final Keyword
  18. Object Cloning
  19. Comparing Objects
  20. Type Hinting
  21. Late Static Bindings
  22. Objects and references
  23. Object Serialization
  24. OOP Changelog