Crack PHP Interview with these questions and answers.These PHP Interview Questions and Answers provide help for both beginners and intermediate.

100% you can crack any php interview if you read these question properly.

From this article you can learn basic and advanced level programs of PHP and impress the interviewer so let’s start with basic.

A. Basic PHP Interview questions and answers

We are start from basic level to advanced level questions.

1.Diffrence between get and post in php?

GetPost
The form information is visible in the URLThe form information is not visible in the URL
We can sent limited data upto 1500 characters.Unlimited data we can sent
Less SecureMost Secure

2. Diffrence between Include and require in php?

IncludeRequire
If the file does not exist then give a warning error and process the execution of the scriptIf the file does not exist then give a fatal error and stop the execution of the script
Both used for include fileBoth used for include file

3. Diffrence between Single quotes ” and double quotes “” in php?

Double “”     Single ‘’
Double quote  evalute the value of variable. Ex. $name = “john smith”;
 echo “My Name is”. “$name”; //Outpout: My name is john smith
Single quote  can not do this.     
Ex. $name = “john smith”; 
echo “My Name is”. ‘$name’;   
//Outpout: My name is $name

4. Diffrence between == and === in php?

Both used for check the equalit.

=====
It is used to check the equality of two operands.It is used to check the equality of two operands and also check the data type of operands
SessionCookie
A php Session is used to store data on a server rather than the local computer.Cookie is used to store data information of user in the local computer.browser.
Session size upto 128 MBCookie size upto 5 MB

6. 5 PHP array and PHP string function.

 5 Array Functions

array_filter - Filters the values of an array using a callback function.

array_walk - Applies a user function to every member of an array.

array_map - Sends each value of an array to a user-made function, which returns new values.

array_combine - Creates an array by using the elements from one “keys” array and one “values” array.

array_merge - Merges one or more arrays into one array.

5 String Function –

strlen() - Return the Length of a String.

strrev() - Reverse a String.

strpos() - Search For a Text Within a String.

str_replace() - Replace Text Within a String.

ltrim() - Removes whitespace or other characters from the left side of a string.

7. What is Sql Injection in php?

Definition – Make changes to the existing query by passing our own value.

Prevent – In php 5.6 version or older version – mysql_real_escape_string().

In a newer version we are using prepared statement.

<?php
      $stmt = $conn->prepare("insert into mytable (fanme,mname,lname)values(?,?,?)");
      $stmt->bind_param("sss",$fname,$mname,$lname);
      //set Parameter
      $fname = "Joe";
      $mname = "cox";
      $lname = "smith";
   ?>

Note – i => int, s=> string, d=>double, b=>binary.

8. What is curl and uses?

PHP curl is a library that is the most powerfull extension of php. It allows the user to create the http request.

<?php
   $ch = curl_init();
   curl_setopt($ch, curlopt=uri, 'www.google.com');
   curl_exec($ch);
?>

9. What is Magic Method in php?

Magic method are special method which override php’s default action when certain action are performed on an object.

Example of magic methods__construct() __destruct() __call() __sleep()

Note – magic method always start with double underscore.

10. What is Magic Constant in php?

They are similar to other predefined constants but as they change their values with the context, they are called magic constants.

Example of magic Constant – __CLASS__ __FUNCTION__ __DIR__
Note – magic constant always start and end with double underscore.

11. Explain Exception handling in php

Exception handling is used to replace the normal flow of code execution if a specified error (exceptional) condition occurs.

<?php
function checkNum($no){
   if($no > 1){
    throw new exception("value must be 1 or below")
    }
 return true;
}

// Trigger exception in a try block -
  try{
    checkNum(2);
    // If the exception is thrown
    echo "if you see the no is 1 or below";
  }
//Catch Exception
  catch(exception $e){
  echo 'Message'. $e->getmessage();
}

 ?>

12. PHP data type

a. string
b. int
c. double
d. boolen (true or false)
e. null
f. resource
g. array
h. object

B. Advanced PHP Interview questions and answers

13. What is abstraction in php?

Abstraction is any representation of data in which the implementation details are hidden.

14. explain Abstract class in php.

An abstract class is a class that contain atleast one abstract method . An abstract method is a method that is declaired, but not implemented in code.
Note – 1. We can not create a instance/object of the abstract class.
2. At least one method must abstract.

<?php
abstract class AbstractClass
{
    abstract protected function prefixName($name);
}
class ConcreteClass extends AbstractClass
{
    public function prefixName($name, $separator = ".") {
        if ($name == "Pacman") {
            $prefix = "Mr";
        } elseif ($name == "Pacwoman") {
            $prefix = "Mrs";
        } else {
            $prefix = "";
        }
        return "{$prefix}{$separator} {$name}";
    }
}
$class = new ConcreteClass;
echo $class->prefixName("Pacman"), "\n";
echo $class->prefixName("Pacwoman"), "\n";

// Output
// Mr. Pacman.
// Mrs. Pacwoman
?>

15. What is Interface in PHP.

An interface allow unrelated classes to implement the same set of method.

Note – 1. We can not create a instance/object of the interface.
2. We can’t declared properties.
3. All method must abstract so can’t implement in the code.
4. We can implement multiple interface in same class.

<?php
 interface Shape {
    public function calculateArea();
    public function calculatePerimeter();
  }


class Rectangle implements Shape {
    private $length;
    private $width;
    
    public function __construct($length, $width) {
        $this->length = $length;
        $this->width = $width;
    }
    
    public function calculateArea() {
        return $this->length * $this->width;
    }
    
    public function calculatePerimeter() {
        return 2 * ($this->length + $this->width);
    }
}

?>

16. What is encapsulation in php?

Wrapping up of a data in a single unit.

17. What is Polymorphism in php?

In which we can provide same set of method in diffrent class.

Type of Polymorphism –

  1. Compile Time / Static Binding / Method Overloading.
  2. Run Time / Dynamic Binding / Method Overriding.

Note – In php Method Overloading not supported in php if we want to do this we use __class method.

18. What is method Overriding in php?

Function overriding is the ability to create multiple functions of the same name with diffrent implementation.

<?php 
 Class A{
   function abc(){
     echo "Hello World";
    }
 }

  Class B extend A{
     function abc(){
       echo "Hello World";  
   }
  }
 ?>

19. What is Traits in PHP.

PHP not supported multiple inheritance so PHP introduce traits.

<?php

  trait TraitName {
    echo "Hello World";
  }
  class myclass{
    use TraitName;
   }

 ?>

20. Explain Self keyword in php.

Used to access a static method or properties within a class.

<?php
   class xyz(){
      private static $static_member = "techlessonhome";
      function __construct() {
        echo self::$static_member;
       // Accessing static variable
     }
   }
?>

21. What is Namespace in php

We cannot add same name class in same file, To solve this problem we used namespace.

Note – php file must have namespace declaration first.

<?php 
  // filename a.php
  class A{
    // Method
  }  ?>

// filename b.php
<?php  class A{
    // Method
  }  ?>

// Filename c.php
 <?php  
  include 'a.php';
  include 'b.php'; ?>
    
// Output - got error.
Example 2 -
<?php // filename a.php 
           namespace a;
          class A{
             //method 
           } ?>


<?php // filename b.php 
           namespace b;
          class A{
             //method 
           } ?>


<?php // filename c.php 
              include 'a.php';
              include 'b.php'; 
      $obj = new a\A();
    // No Error;
?>

22. What is Solid Principle.

Solid Principal based on 5 Principle.

  1. Single Responsibility – Class should be responsible for single task.
  2. Open/Close – Class should be open for extension and close for modification.
  3. Liskov Subsitute – Drived class should be subsitute of base class.
  4. Interface Sagregration – Do not declaired multiple method inside one interfece instead of this we create multiple interface.
  5. Dependancy Inversion.

Please see our SOLID Principles article for a detailed explanation.

23. Design Pattern in php.

In software engineering, a Design Pattern is a general repeatable solution to commonly occurring problem in software Design. Good Object-oriented designs should be reusable, maintainable and extensible and Design Patterns in PHP could be very helpful in doing that. It does not only help in solving problems, it implies an optimal way addressing common challenges

1.Singleton

Single point of access create only once instance when you don’t want multiple copies of class.

<?php

class myconn
{
  private static $obj;
  function __construct()
  {
    echo __CLASS__ . "Only Once";
  }
  function setconn()
  {
    if (!isset(self::$obj)) {
      self::$obj = new myconn();
    }
    return self::$obj;
  }
}

$object = myconn::setconn(); // myconn only once
$object1 = myconn::setconn(); // 

?>
2. Dependency Injection

Minimize repetitive code work, reusing code and injecting the object of a class into another class.

3. Proxy.

4. Builder.

5. Facade

C. PHP Basic Programs

Please read our PHP Programs series to improve reasoning power.

For latest update please follow our YouTube and Facebook.

By admin

Leave a Reply

Your email address will not be published. Required fields are marked *