PHP interview questions

PHP interview questions

This is list of questions that i was asked on interviews for PHP and Web developer positions.

What is the difference between ‘ and “ quote types?

Single quoted strings will display things almost completely “as is.” Variables and most escape sequences will not be interpreted. The exception is that to display a literal single quote, you can escape it with a back slash ', and to display a back slash, you can escape it with another backslash \ (So yes, even single quoted strings are parsed).
Double quote strings will display a host of escaped characters (including some regexes), and variables in the strings will be evaluated. An important point here is that you can use curly braces to isolate the name of the variable you want evaluated. For example let’s say you have the variable $type and you what to echo “The $types are” That will look for the variable $types. To get around this use echo “The {$type}s are” You can put the left brace before or after the dollar sign. Take a look at string parsing to see how to use array variables and such

Do you have experience with any frameworks? Existing / Custom?

I have wrote my own framework for one project, but also I have used Zend, Symfony, CodeIgniter.

What is the difference between == and ===?

Operator == check if values are equal and operator === check if values are equal by type and value

What is the difference between include and require (_once)? When would you use them?

The require() function is identical to include(), except that it handles errors differently. If an error occurs, the include() function generates a warning, but the script will continue execution. The require() generates a fatal error, and the script will stop.
The require_once() statement is identical to require() except PHP will check if the file has already been included, and if so, not include (require) it again.

Access modifiers? Difference between private and protected?

public scope to make that variable/function available from anywhere, other classes and instances of the object.
private scope when you want your variable/function to be visible in its own class only.
protected scope when you want to make your variable/function visible in all classes that extend current class including the parent class.

Is it possible to access user browser information from PHP?

Yes, we can use $_SERVER[‘HTTP_USER_AGENT’] to get info about user agent.

How would you debug your PHP application?

I am using xdebug which is configured to work with PHP Storm. Also it has extensions from chrome which makes debugging easier.

How do you access URL parameters? GET vs POST vs REQUEST?

For accessing parameters in HTTP Request METHODS we will use variables $_GET, $_POST or $_REQUEST.
GET: Can be cached and bookmarked, parameters remain in browsing history, data length in url is restricted to 2048 characters, encoding type is application/x-www-form-urlencoded, parameters remains in browser history, only ASCII characters allowed, less secured - don’t send passwords with GET, data is visible in url
POST: Cannot be cached and bookmarked, parameters are not saved in browser history, no restrictions on data length, encoding type is application/x-www-form-urlencoded or multipart/form-data for binary data, ASCII and binary data is also allowed, POST is safer because parameters are not stored in browser history or in web server logs, data is not displayed in url
REQUEST: Associative array that by default contains contents of $_GET, $_POST and $_COOKIE.

How can you pass a PHP object to another application? Different encodings / escaping.

Object in PHP can be serialized and then saved to file or database. We can use function serialize/unserialize and base64_encode/base64_decode.

Could you use $this in a static method?

It is not possible to use $this in static method because $this is not allowed to use if is not in object context.

Difference between this and self?

$this refers to the instance of the class. In PHP there is also something called static state, which is the same for all instances of that class. self:: is the accessor for those attributes and functions.

How would you improve the performance of your PHP script / application?

We can use caching like APC, OPcache or Memcached.
APC is a PHP extension that runs on PHP 5.4 and earlier versions. Because it is a separate extension, it may or may not already be installed on your server.
OPcache is a drop-in replacement for APC that runs on PHP 5.5 and later versions. OPcache is a core component built into PHP, so it does not require separate installation like APC does.
Memcached is a high-performance, distributed memory object caching system, generic in nature, but intended for use in speeding up dynamic web applications by alleviating database load.

What is difference between define() and const

The fundamental difference between those two ways is that const defines constants at compile time, whereas define defines them at run time.
Some disadvantages of const are:

  • const cannot be used to conditionally define constants. To define a global constant, it has to be used in the outermost scope:
    if(...) {
      const FOO = 'BAR';// invalid
    if(...) {
      define('FOO', 'BAR');// valid
  • const takes a plain constant name, whereas define() accepts any expression as name. This allows to do things like this:
    for($i = 0; $i < 32; $i++) {
      define('BIT_' . $i, 1 << $i);
  • const is always case sensitive, whereas define() allows you to define case insensitive constants by passing true as the third argument:
    define('FOO', 'BAR', true);
    echo FOO; // BAR
    echo foo; // BAR

How would you analyze the performance of your PHP application? Any experience with profilers?

In production environment I was using newrelic monitoring software. Also I have used Blackfire, XHProf, KCacheGrind.

Are you familiar with the template engines? Uses? What purpose do they serve?

I have used Smarty template engine, after that Twig. Some facts:

  • separation between html and php and better collaboration between programmers and designers
  • readability of code
  • caching
  • built in features
  • easy to learn

What is the difference between passing by value and passing by reference?

  • When a parameter is passed by value, the caller and callee have two independent variables with the same value. If the callee modifies the parameter variable, the effect is not visible to the caller.
  • When a parameter is passed by reference, the caller and the callee use the same variable for the parameter. If the callee modifies the parameter variable, the effect is visible to the caller’s variable.

How would you access global variables? Why is it a bad practice / anti pattern?

We can access global variables via variable $GLOBALS (associative array) which is reference to all variables available in global scope. If we want for example to access some global variable in function we can also say global $var_name, and it will point to global variable $var_name.
When using global variables readability of code becomes very low, because it is hard to track which function is changing that variable. On other side if you use global variables it doesn’t mean that you are bad programmer, sometimes is handy to use global variables because it reduces amount of code that you need to write.

How would you analyze application issues on a production system?

In most cases I am looking at error and access logs.

Is it possible to suppress a possible warning / error that could be thrown by a function? Why is that a bad practice / anti pattern? Possible uses?

Yes, it is possible. It is bad practice because it can lead to creating a lot of errors which are not visible and later total fail of system.
Sometimes it is suitably to use error suppressor: when accessing parameters from HTTP METHODS, instead of checking isset parameter we can use error suppressor and automatically assign null to parameter if is not set.

How would you prevent overriding a method from your class? Could you make a class field final?

We can prevent overriding a method in class with keyword final. Class fields cannot be declared final.

class A
    final public function test()
        echo "You cannot override me!";

Floating point arithmetics? Precision and possible problems?

What causes the error ‘Warning: Cannot modify header information - headers already sent’. How would you diagnose it?

This error message gets triggered when anything is sent before you send HTTP headers (with setcookie or header).

  • Accidental whitespace, often at the beginning or end of files, like this:
    // Note the space before "<?php"
  • Byte order marks at the beginning of a php file. Examine your php files with a hex editor to find out whether that’s the case. They should start with the bytes 3F 3C. You can safely remove the BOM EF BB BF from the start of files.
  • Explicit output, such as calls to echo, printf, readfile, passthru, code before <? etc.
  • A warning outputted by php, if the display_errors php.ini property is set. Instead of crashing on a programmer mistake, php silently fixes the error and emits a warning. While you can modify the display_errors or error_reporting configurations, you should rather fix the problem. Common reasons are accesses to undefined elements of an array (such as $_POST[‘input’] without using empty or isset to test whether the input is set), or using an undefined constant instead of a string literal (as in $_POST[input], note the missing quotes).

Turning on output buffering should make the problem go away; all output after the call to ob_start is buffered in memory until you release the buffer, e.g. with ob_end_flush.

What is self? What is static?

self refers to the same class in which the new keyword is actually written.
static, in PHP 5.3’s late static bindings, refers to whatever class in the hierarchy you called the method on.

class A {
    public static function get_self() {
        return new self();

    public static function get_static() {
        return new static();

class B extends A {}

echo get_class(B::get_self());  // A
echo get_class(B::get_static()); // B
echo get_class(A::get_self()); // A
echo get_class(A::get_static()); // A

Is there a function that can return changed values for some array?

That function in php is array_map.
array_map() returns an array containing all the elements of array1 after applying the callback function to each one. The number of parameters that the callback function accepts should match the number of arrays passed to the array_map()

array_map ( callable $callback , array $array1 [, array $... ] ) : array

What is ORM, did you used one?

Object-Relational Mapping (ORM) is a technique that lets you query and manipulate data from a database using an object-oriented paradigm. When talking about ORM, most people are referring to a library that implements the Object-Relational Mapping technique, hence the phrase “an ORM”.
An ORM library is a completely ordinary library written in your language of choice that encapsulates the code needed to manipulate the data, so you don’t use SQL anymore; you interact directly with an object in the same language you’re using.
Some of PHP ORM libraries: Doctrine ORM, Propel, ReadBeanPHP.

Simo Software developer
comments powered by Disqus