Vaidikalaya

PHP Interview - Intermediate Level

If you complete your basic label interview question - answers then prepare an intermediate label. Here we discuss Class, Interface, and traits-related question-answers.


1) What is OPPS in PHP?

OOP stands for Object-Oriented Programming. Classes and objects are the two main aspects of object-oriented programming.

Object-oriented programming has several advantages over procedural programming:

  • OOP is faster and easier to execute
  • OOP provides a clear structure for the programs
  • OOP makes it possible to create fully reusable applications with less code and shorter development time

There are some major principles of OPPS:

  • Encapsulation
  • Inheritance
  • Polymorphism
  • Abstraction

2) What are Classes and Objects in PHP?

Class:

Class is the programmer-defined data type, which includes local functions as well as local data. You can think of a class as a template for making many instances of the same kind (or class) of the object.

Object:

The object is an individual instance of the data structure defined by a class. You define a class once and then make many objects that belong to it. Objects are also known as instances.

Example:

ClassObject
Fruit
Apple
Banana
Mango
CarVolvo
Audi
Toyota

A class is a template for objects, and an object is an instance of the class. When the individual objects are created, they inherit all the properties and behaviors from the class, but each object will have different values for the properties.


3) How to make classes and objects in PHP?

A class is defined by using the class keyword, followed by the name of the class and a pair of curly braces ({}). All its properties and methods go inside the braces:

<?php      
Class Fruit{

}
?>

Objects of a class are created using the new keyword. Classes are nothing without objects! We can create multiple objects from a class. Each object has all the properties and methods defined in the class, but they will have different property values.

<?php      
Class Fruit{

}
$object = new Fruit()
?>


Example
<?php      
Class Fruit{

    //properties
    public $fruitName;

    //methods
    function set_name($name){
        $this->fruitName = $name;
    }
    function get_name(){
       echo $this->fruitName."\n";
    }
}

//objects
$apple=new Fruit();
$banana=new Fruit();

//call methods
$apple->set_name('Apple');
$banana->set_name('Banana');

$apple->get_name();
$banana->get_name();
?>


Note: In a class, variables are called properties, and functions are called methods!


4) Why does use $this in PHP?

$this is a reserved keyword in PHP and It refers to the current object. It allows you to access the properties and methods of the current object within the class using the object operator(->).

The $this keyword is only available within a class. It doesn’t exist outside of the class. If you attempt to use the $this outside of a class, you’ll get an error.

Example 1: Access Properties
<?php
Class Student{
    public $studentName;
    public function set_name($name){
        //Access $studntName using $this keyword
        $this->studentName=$name;
    }
    public function get_name(){
        echo $this->studentName;
    }
}

$obj=new Student();
$obj->set_name('John');
$obj->get_name();


Example2: Access Methods
<?php
Class Student{
    public $firstName;
    public $lastName;
    public function set_name($firstname,$lastname){
        //Access $studntName using $this keyword
        $this->firstName=$firstname;
        $this->lastName=$lastname;
        //Call full_name method
        $this->full_name();
    }
    public function full_name(){
        echo $this->firstName.' '.$this->lastName;
    }
}
$obj=new Student();
$obj->set_name('John','Anderson');

5) What are chaining methods in PHP

Method Chaining is the concatenation of multiple methods to increase the readability of code and avoid putting all the code in a single function. Method Chaining is a way to keep calling multiple methods in a single line one after another such as:

Example
<?php
Class Student{
    public $name,$subject;
    public function set_name($name){
        $this->name=$name;
    }
    public function set_subject($subject){
        $this->subject=$subject;
    }
    public function display(){
        echo $this->name."\n".$this->subject."\n";
    }
}
$obj=new Student();
//normal way
$obj->set_name('John');
$obj->set_subject('English');
$obj->display();

Example - Chaining Method
<?php
Class Student{
    public $name,$subject;
    public function set_name($name){
        $this->name=$name;
        return $this;
    }
    public function set_subject($subject){
        $this->subject=$subject;
        return $this;
    }
    public function display(){
        echo $this->name."\n".$this->subject."\n";
    }
}
$obj=new Student();
//Chaining Way
$obj->set_name('John')
    ->set_subject('Math')
    ->display();


NOTE: every method has to return $this object instance to perform the chaining method.


6) What are constructors and destructors in PHP?

Constructor:

In object-oriented programming terminology, a constructor is a method defined inside a class that is called automatically at the time of the creation of an object. The purpose of a constructor method is to initialize the object. In PHP, you can create constructors with a construct keyword followed by double underscores(__).

Syntex
function __construct(){
        //initialize the object and its properties by assigning values
}


Example
<?php
class Test{
    function __construct(){
        echo "Hello World";
    }
}
$obj=new Test();


Destructor:

destructor is a method defined inside a class that is called automatically at the end of the script. Destructors give chance to objects to free up memory allocation so that enough space is available for new objects or free up resources for other tasks.  In PHP, you can create destructors with a destruct keyword followed by double underscores(__).

Syntex
function __destruct(){
       //destroying the object or cleaning up resources here
}


Example
<?php
class Test{
    function __construct(){
        echo "Object initialized\n";
    }
    function __destruct(){
        echo "Object destroyed";
    }
}
$obj=new Test();



7) Difference between constructor and destructor.

ConstructorDistructor
Constructor is involved automatically when the object is created.Destructor is involved automatically when the object is destroyed.
function name is _construct().
function name is _destruct()
Accepts one or more arguments.
No arguments are passed. It's void.
Constructors can be overloaded.
Destructors cannot be overloaded.
Multiple constructors can exist in a class.
Only one Destructor can exist in a class.
Allocates memory.
It deallocates memory.

8) What are static methods and properties in PHP?

Static methods and properties can be called directly - without creating an instance (object) of a class.

Static methods and properties are declared with the static keyword. To access a static method and property use the class name, a double colon (::), and the method or property name:

NOTE: 
1. Static methods cannot access non-static methods and variables.
2. Static method will not have access to $this (as there is no $this to talk about in a static context).

Example
<?php
class Test{
    public static $name = "Vaidikalaya";
    public static function display(){
        echo "Hello Vaidikalaya\n";
    }
}
//access static method
Test::display();

//access static property
echo Test::$name;

?>

9) How to access static methods and properties in the same class in PHP?

A static method and property can be accessed from a method in the same class using the self keyword and double colon (::).

Example 1
<?php
class Test{
    public static $firstname = "Arjun";
    public static $lastname = "Sharma";
    public function fullname(){
        //access static properties
        echo self::$firstname.' '.self::$lastname;
    }
}
$obj=new Test();
$obj->fullname();
?>


Example 2
<?php
class Test{
    public static function siteName(){
        echo "Vaidikalaya";
    }
    public function showSite(){
        self::siteName();
    }
}
$obj=new Test();
$obj->showSite();
?>



10) What is inheritance in PHP?

Inheritance is an important principle of object-oriented programming. It is the phenomenon by which a child class can inherit all the properties and characteristics of the parent class. PHP offers mainly three types of inheritance based on their functionality. These three types are as follows:

  • Single Inheritance
  • Hierarchical Inheritance
  • Multilevel Inheritance

The keyword extends is used to add a parent class to a child class.

Syntex
Class ParentClass{
    //properties, constants and methods of Parent Class
}
Class ChildClass extends ParentClass{
    //public and protected methods inherited from parent class
}


Example 1: Access Parent Methods With Objects
<?php
class Test1{
    public function display1(){
        echo "I am Parent\n";
    }
}

class Test2 extends Test1{
    public function display2(){
        echo "I am Child";
    }
}
$child_obj=new Test2();
//we can access the parent methods from the child object;
$child_obj->display1();


Example 2: Access Parent Methods With $this keyword.
<?php
class Test1{
    public function display1(){
        echo "I am Parent\n";
    }
}

class Test2 extends Test1{
    public function display2(){
        $this->display1();
        /*you can access parent methods or properties,
        using this keyword inside the child methods*/
    }
}
$child_obj=new Test2();
$child_obj->display2();



11) What are Access Modifiers in PHP?

There are three access modifiers in PHP:

  • public: the property or method can be accessed from everywhere. This is the default.
  • protected: the property or method can be accessed within the class and by classes derived from that class.
  • private: the property or method can ONLY be accessed within the class.

12)How to archive multiple inheritances in PHP?

PHP doesn’t support multiple inheritances but by using Interfaces or Traits in PHP, we can implement it.


13) What are the traits of PHP?

A trait is similar to a class, but it is only for grouping methods in a fine-grained and consistent way. Traits are used to declare methods that can be used in multiple classes. Traits can have methods and abstract methods that can be used in multiple classes, and the methods can have any access modifier (public, private, or protected).

Traits are declared with the trait keyword and use a trait in a class, use the use keyword

Example
<?php
//trait for addition
Trait Addition{
    public function add($num1,$num2){
        return $num1+$num2;
    }
}

//trait for multiplication
Trait Multiplication{
    public function multiply($num1,$num2){
        return $num1*$num2;
    }
}

class Calculator{
    //access traits using use keyword
    use Addition,Multiplication;
    public function calculate($num1,$num2){
        //access trait's add and multiply method
        $sum=$this->add($num1,$num2);
        $mul=$this->multiply($num1,$num2);

        echo "Addition: ".$sum."\n";
        echo "Multiplication: ".$mul."\n";
    }
}

$obj=new Calculator;
$obj->calculate(10,20);



14) What are Abstract Classes and Methods in PHP?

An abstract class is a class that contains at least one abstract method. An abstract method is a method that is declared but not implemented in the code. We can not make objects for abstract classes so for using abstract methods we need to extend child classes where we implement those methods. And an abstract class can contain abstract as well as nonabstract methods.

An abstract class or method is defined with the abstract keyword

when a child class is inherited from an abstract class, we have the following rules:

  • The child class method must be defined with the same name and it redeclares the parent abstract method.
  • The child class method must be defined with the same or a less restricted access modifier.
  • The number of required arguments must be the same. However, the child class may have optional arguments in addition.


Example
<?php
abstract class Student{
    //abstract method can only be defined not declared;
    abstract public function setStudentDetail($name,$email,$phone);
    abstract public function displayData();
}

class FillData extends Student{
    public $studentName,$studentEmail,$studentPhone;
    public function setStudentDetail($name,$email,$phone){
        $this->studentName=$name;
        $this->studentEmail=$email;
        $this->studentPhone=$phone;
    }
    public function displayData(){
        echo $this->studentName."\n";
        echo $this->studentEmail."\n";
        echo $this->studentPhone."\n";
    }
}

$obj=new FillData();
$obj->setStudentDetail('Test','test@gmail.com','8562445236');
$obj->displayData();

15) What are interfaces in PHP?

Interfaces allow you to create code that specifies which methods a class must implement. Interfaces are defined in the same way as a class, but the interface keyword is used instead of class. And to implement an interface, a class must use the implements keyword.

Interfaces have the following rules:

  • Interfaces cannot have properties(variables).
  • All methods in an interface must be public
  • All methods in an interface are abstract, so they cannot be implemented in code and the abstract keyword is not necessary.
  • Interfaces can't maintain Non-abstract methods.
Syntex
<?php
interface InterfaceName {
  public function method1();
  public function method2($name, $color);
}


Example:
<?php
interface Fruits{
    public function color();
}

Class Apple implements Fruits{
    public function color(){
        echo "red\n";
    }
}

Class Banana implements Fruits{
    public function color(){
        echo "yellow";
    }
}

$objApple=new Apple();
$objApple->color();

$objBanana=new Banana();
$objBanana->color();