loader spinner

PHP interview questions and answers (beginner to moderate)

May 19, 2019 1:22pm - 9 min read

Last updated on: January 31, 2020 5:50am

These are a few PHP related questions for an interview (beginner & moderate level). Advanced level will coming soon.

 

Beginner Moderate
What is juggling in PHP? What is overloading and overriding in PHP?
Difference between === and == in PHP ? How to prevent class inheritance or to prevent method overriding?
Why would you use === instead of ==? What are Traits?
Difference between $ and $$ in PHP ? How does one prevent the following Warning ‘Warning: Cannot modify header information – headers already sent’ and why does it occur in the first place?
Difference between echo vs print What are SQL Injections, how do you prevent them and what are the best practices?
Difference between include vs require What are PHP Magic Methods/Functions?
What are the main error types in PHP and how do they differ? How can you encrypt password using PHP?
How can you enable error reporting in PHP? How to connect to a URL in PHP?
What is the difference between GET and POST? What is the difference between run time exception and compile time exception?
What are the common uses of PHP? What is the use of callback in PHP?
What is PEAR in PHP?
What are the two most common ways to start and finish a PHP block of code?
What are the 3 scope levels available in PHP and how would you define them?

What is juggling in PHP?

Type Juggling means dealing with a variable type. In PHP a variable type is determined by the context in which it is used. If an integer value is assigned to a variable, it becomes an integer.

According to PHP.net,

PHP does not require (or support) explicit type definition in variable declaration; a variable’s type is determined by the context in which the variable is used. That is to say, if a string value is assigned to variable $var, $var becomes a string. If an integer value is then assigned to $var, it becomes an integer.

For example,

$foo = "1";
$foo *= 2;
echo $foo;

Output:

2

Another example:

$foo = 10;   
$bar = (boolean) $foo; 
echo $bar;

Output:

1

Difference between === and == in PHP ?

The difference between the two is that ‘==’ should be used to check if the values of the two operands are equal or not. On the other hand, ‘===’ checks the values as well as the type of operands.

if("22" == 22) {
    echo "YES";
} else {
    echo "NO";
}

Output:

Yes

The code above will print “YES”. The reason is that the values of the operands are equal.

if("22" === 22) {
    echo "YES";
} else {
    echo "NO";
}

Output:

No

The result we get is “NO”. The reason is that although values of both operands are same but their types are different, “22” (with quotes) is a string while 22 (w/o quotes) is an integer.

Why would you use === instead of ==?

 

Difference between $ and $$ in PHP ?

The $ operator in PHP is used to declare a variable. In PHP, a variable starts with the $ sign followed by the name of the variable. For example, below is a string variable:

$var_name = "Hello World!";

The $var_name is a normal variable used to store a value. It can store any value like integer, float, char, string etc. On the other hand, the $$var_name is known as reference variable where $var_name is a normal variable. The $$var_name used to refer to the variable with the name as value of the variable $var_name. For example:

$Hello = "Hello Nirvana";
$var = "Hello";
echo $var;
echo $$var;

Output:

Hello
Hello Nirvana

Difference between echo vs print

They are both used to output data to the screen. echo has no return value while print has a return value of 1 so it can be used in expressions. echo can take multiple parameters (although such usage is rare) while print can take one argument. echo is marginally faster than print .

Difference between include vs require

Neither include or require are functions, they are constructs. It is therefore not necessary to call them using parentheses like

include('file.php');

instead it is preferred to use

include 'file.php'

The difference between include and require arises when the file being included cannot be found: include will emit a warning (E_WARNING) and the script will continue, whereas require will emit a fatal error (E_COMPILE_ERROR) and halt the script.
If the file being included is critical to the rest of the script running correctly then you need to use require.
include_once and require_once behave like include and require respectively, except they will only include the file if it has not already been included. Otherwise, they throw the same sort of errors.

So to summarize, they both include a specific file but on require the process exits with a fatal error if the file can’t be included, while include statement may still pass and jump to the next step in the execution.

What are the main error types in PHP and how do they differ?

In PHP there are three main type of errors:

  • Notices – Simple, non-critical errors that are occurred during the script execution. An example of a Notice would be accessing an undefined variable.
  • Warnings – more important errors than Notices, however the scripts continue the execution. An example would be include() a file that does not exist.
  • Fatal – this type of error causes a termination of the script execution when it occurs. An example of a Fatal error would be accessing a property of a non-existent object or require() a non-existent file.

How can you enable error reporting in PHP?

Check if “display_errors” is equal “on” in the php.ini or declare “ini_set('display_errors', 1)” in your script.
Then, include “error_reporting(E_ALL)” in your code to display all types of error messages during the script execution.

What is the difference between GET and POST?

  • GET displays the submitted data as part of the URL, during POST this information is not shown as it’s encoded in the request.
  • GET can handle a maximum of 2048 characters, POST has no such restrictions.
  • GET allows only ASCII data, POST has no restrictions, binary data are also allowed.
  • Normally GET is used to retrieve data while POST to insert and update.

What are Traits?

Traits are a mechanism that allows you to create reusable code in languages like PHP where multiple inheritance is not supported. A Trait cannot be instantiated on its own.

What are the 3 scope levels available in PHP and how would you define them?

Private – Visible only in its own class
Public – Visible to any other code accessing the class
Protected – Visible only to classes parent(s) and classes that extend the current class

What is overloading and overriding in PHP?

Function overloading and overriding is the OOPs feature in PHP. In function overloading, more than one function can have same method signature but different number of arguments. But in case of function overriding, more than one functions will have same method signature and number of arguments.
OverridingOverriding is only pertinent to derived classes, where the parent class has defined a method and the derived class wishes to override that method. An example of overriding:

class Foo { 
  function myFoo() { 
    return "Foo"; 
  } 
} 
class Bar extends Foo { 
  function myFoo() { 
    return "Bar"; 
  } 
} 
$foo = new Foo; 
$bar = new Bar; 
echo($foo->myFoo()); //"Foo"
echo($bar->myFoo()); //"Bar"

Another example: Inherited methods can be overridden by redefining the methods (use the same name) in the child class.
Look at the example below. The __construct() and intro() methods in the child class (Strawberry) will override the __construct() and intro() methods in the parent class (Fruit):

 
class Fruit { 
  public $name; public $color; 
  public function __construct($name, $color) { 
    $this->name = $name;
    $this->color = $color; 
  }
  public function intro() {
    echo "The fruit is {$this->name} and the color is {$this->color}."; 
  }
}

class Strawberry extends Fruit {
  public $weight;
  public function __construct($name, $color, $weight) {
    $this->name = $name;
    $this->color = $color;
    $this->weight = $weight; 
  }
  public function intro() {
    echo "The fruit is {$this->name}, the color is {$this->color}, and the weight is {$this->weight} gram."; 
  }
}

$strawberry = new Strawberry("Strawberry", "red", 50);
$strawberry->intro();

Overloading – Function overloading contains same function name and that function preforms different task according to number of arguments. In PHP function overloading is done with the help of magic function __call().

An example:

class shape { 
// __call is magic function which accepts 
// function name and arguments 
function __call($name_of_function, $arguments) { 		
  // It will match the function name 
  if($name_of_function == 'area') { 	
    switch (count($arguments)) { 		
	// If there is only one argument 
	// area of circle 
	case 1: 
	  return 3.14 * $arguments[0]; 			
	// IF two arguments then area is rectangel; 
	case 2: 
	  return $arguments[0]*$arguments[1]; 
	} 
     } 
   } 
} 
	
$s = new Shape; 
	
echo($s->area(2)); 
echo "n"; 

echo ($s->area(4, 2)); 

How to prevent class inheritance or to prevent method overriding?

The final keyword can be used to prevent class inheritance or to prevent method overriding.
The following example shows how to prevent class inheritance:

final class Fruit {
  // some code
}

// will result in error
class Strawberry extends Fruit {
  // some code
}

The following example shows how to prevent method overriding:

class Fruit {
  final public function intro() {
    // some code
  }
}

class Strawberry extends Fruit {
  // will result in error
  public function intro() {
    // some code
  }
}

How does one prevent the following Warning ‘Warning: Cannot modify header information – headers already sent’ and why does it occur in the first place?

What are SQL Injections, how do you prevent them and what are the best practices?

Last updated on: January 31, 2020 5:50am