PHP Interview Questions
PHP Interview Questions
PHP Interview Questions
What is PHP?
PHP: Hypertext Preprocessor is open source server-side scripting language that is widely used for web development.
PHP scripts are executed on the server. PHP allows writing dynamically generated web pages efficiently and
quickly. The syntax is mostly borrowed from C, Java and perl. PHP is free to download and use.
PEAR(PHP Extension and Application Repository) is a framework and repository for reusable PHP components.
PEAR is a code repository containing all kinds of php code snippets and libraries.
PEAR also offers a command-line interface that can be used to automatically install "packages".
We can achieve the above task by using JavaScript code linked to an event trigger of any form field and call the
document.form.submit() function in JavaScript code.
echo() and print() are language constructs in PHP, both are used to output strings. The speed of both statements is
almost the same.
echo() can take multiple expressions whereas print cannot take multiple expressions.
Print return true or false based on success or failure whereas echo doesn't return true or false.
$message is a variable with a fixed name. $$message is a variable whose name is stored in $message.
Notices, Warnings and Fatal errors are the types of errors in PHP
Notices:
Notices represents non-critical errors, i.e. accessing a variable that has not yet been defined. By default, such errors
are not displayed to the user at all but whenever required, you can change this default behavior.
Warnings:
Warnings are more serious errors but they do not result in script termination. i.e calling include() a file which does
not exist. By default, these errors are displayed to the user.
Fatal errors:
Fatal errors are critical errors i.e. calling a non-existent function or class. These errors cause the immediate
termination of the script.
What is MIME?
MIME types represents a standard way of classifying file types over Internet.
Web servers and browsers have a list of MIME types, which facilitates files transfer of the same type in the same
way, irrespective of operating system they are working in.
A MIME type has two parts: a type and a subtype. They are separated by a slash (/).
MIME type for Microsoft Word files is application and the subtype is msword, i.e. application/msword.
Write the statements that are used to connect PHP with MySQL
The statements that can be used to connect PHP wil MySQL is:
<?
$conn = mysql_connect('localhost');
echo $conn;
?>
This statement gets the resource of the localhost. There are other different ways with which you can connect to
the database and they are as follows:
<?
mysql_connect('db.domain.com:33306','root','user');
mysql_connect('localhost:/tmp/mysql.sock');
mysql_connect('localhost','rasmus','foobar',
true,MYSQL_CLIENT_SSL|MYSQL_CLIENT_COMPRESS);
?>
How to use HTTP Headers inside PHP? Write the statement through which it can be added?
HTTP headers can be used in PHP by redirection which is written as:
<?header('Location: http://www.php.net')?>
The headers can be added to HTTP response in PHP using the header(). The response headers are sent before any
actual response being sent. The HTTP headers have to be sent before taking the output of any data. The statement
above gets included at the top of the script.
How the web server interprets PHP and interacts with the client?
After installing and configuring the PHP, the web When PHP is installed, the Web server looks for PHP code that is
embedded in HTML file with its extension. The extensions which are used are .php or .phtml. When web server
receives a request for the file with an appropriate extension, HTML statements are processed and PHP statements
are executed on the server itself. When the processing gets over the output is being shown in HTML statements.
What are the different types of statements that are present in PHP?
There are four kinds of PHP statements that are present. They are as follows:
• Simple statement- these are the echo statements and end with a semicolon (;). PHP ignores white spaces
between simple statements. Until it finds a semicolon it reads the statement.
• Complex/Conditional statements: these are the statements which deal with certain conditions that have to be
executed to meet certain specific requirements. These are if and else block or switch statements. PHP reads the
complete statement and doesn’t stop at the first semicolon it encounters. It looks for starting and ending braces to
end the execution.
• Looping statements: statements that are repeated in a block. The feature that enables you to execute the
statements repeatedly is called as loop. For example: for loop, while loop, do..while loop.
How can we increase the execution time of a php script?
By the use of void set_time_limit(int seconds)
Set the number of seconds a script is allowed to run. If this is reached, the script returns a fatal error. The default
limit is 30 seconds or, if it exists, the max_execution_time value defined in the php.ini. If seconds is set to zero, no
time limit is imposed.
When called, set_time_limit() restarts the timeout counter from zero. In other words, if the timeout is the default
30 seconds, and 25 seconds into script execution a call such as set_time_limit(20) is made, the script will run for a
total of 45 seconds before timing out.
I've been interviewed by many companies for PHP development positions, every company has a
slightly different interview process, but there seems to be a lot of commonalities among them.
I've outlined below the main areas that companies look for knowledge in, and some
questions/answers you may get asked. At the end of the day you will not be able to entirely fake
your way through a good interview, but I thought this would be a huge help for newer or mid
level developers going into an interview. If you are totally new to PHP or programming
www.teamtreehouse.com is a great place to start. Don't forget to me on Twitter so you can stay
up to date with whats going on in the PHP world.
likelihood high
This is usually a pretty open ended question. You should understand classes (objects are
instantiated classes), abstract classes, interfaces, methods, properties,inheritance, multiple
inheritance as well as why OOP is helpful as compared to procedural programming.
http://net.tutsplus.com/tutorials/php/object-oriented-php-for-beginners/
likelihood high
Interfaces do not contain business logic, only method signatures that define a template
that any classes implementing the interface must contain. Lets take an auto mobile for
example. If we were to create and interface for a car we would want to define a few
methods like drive, stop, turn left , turn right. This mean that any vehicle that is a car (aka
implements the interface car) must have methods for these things, If they do not PHP will
throw an error. So if your car is an BMW , Honda or Ford it must be able to stop. How it
stops is up to each car (or PHP class) but it must be able to stop. Technically we can
decide not to use an interface for cars, but then some types of cars are not forced to have
a "stop" method.
3. What is MVC?
likelihood high
Most programmers know this, but interviewers will likely look for a deep understanding
of MVC, and some explanation or examples on how/why/ when you used it.
MVC- Model, View, Controller - is simply a way of organizing your code into 3 separate
layers each with there own job.
Model - Usually contains data access code and all of you business logic code.
View - Contains markup/design code, generally html,xml, json.
Controller - Usually contains very little code, just whatever is needed to call the Model
code and render the View code.
http://www.symfony-project.org/book/1_0/02-exploring-symfony-s-code
likelihood high
A PHP session cookie is set in the clients browser, on every request the client sends that
cookie to the server. PHP then uses that cookie to select the corresponding session
information. By default PHP session_start() will store session data in files, you can also
store sessions in a database.
http://www.php.net/manual/en/function.session-start.php
5. What are some of the big changes PHP has gone through in the past few years?
likelihood high
There are a number, but the big ones people are looking for are:
a. PHP 5.0 realised the object model (AKA OOP).
b. 5.1 added PDO - for accessing databases.
c. 5.3 - added namespace support and late static bindings.
http://en.wikipedia.org/wiki/PHP#Release_history
likelihood high
This is a great question because an interviewer can tell how deeply you understand HTTP
and the request/response. If you don't have good understanding of HTTP protocol, google
around and get a grasp on it.
Good answer
Explain the HTTP protocol and how every request contains a method,
generally(GET,POST,PUT,DELETE) and what each method signifies.
Bad answer
$_GET stores variables passed in url as query strings. $_POST stores variables past from
using method = $_POST
http://djce.org.uk/dumprequest
7. In a PHP class what are the three visibility keywords of a property or method?
likelihood medium
public, private and protected. The default is public.
Public -> Any class may instantiate the class and call the method or property.
Protected -> Only the class itself or inherited (children) classes may call a method or
property.
Private -> Only the class itself may call a method or property.
http://php.net/manual/en/language.oop5.visibility.php
8. What is Polymorphism?
likelihood medium
Don't get scared by the big word. It's simply the idea that one object can can take on
many forms. So in PHP OOP one class "cars" may have two classes that extend it, for
example a "Honda" class and a "BMW" class.
http://stackoverflow.com/questions/210460/try-to-describe-polymorphism-as-easy-as-
you-can
likelihood medium
They are trying to gauge your understanding of how class auto loading works. Review
the "autoload" and "spl_autoload_register" function (note:you should use the later). The
autoload function basically triggers a function when a class is instantiated, you can put
whatever logic you like in it but generally you want to include the class file based on
some sort of naming convention.
http://www.php.net/manual/en/function.spl-autoload-register.php
likelihood medium
$wed= 1;
$day = ($wed==1) ? 'today' : 'tommorrow';
// $day is now set to 'today'
Companies often ask about the ternary operator (?). which is simply a shorthand for if
else statements.
http://davidwalsh.name/php-shorthand-if-else-ternary-operators
likelihood medium
"::" double colons is the scope operator it is used to call methods of a class that has not
been instantiated. You should also understand static methods and how they differ from
regular methods.
http://www.php.net/manual/en/language.oop5.paamayim-nekudotayim.php
http://php.net/manual/en/language.oop5.static.php
12. What are some PHP Design patterns you have worked with?
likelihood medium
Design patterns are simply commonly used techniques within your code, they often are
implemented in different ways so they can be a bit tricky to grasp without writing them
yourself. If you are unfamiliar with them I would start by learning the Singleton Pattern
and the Strategy Pattern.
http://www.ibm.com/developerworks/library/os-php-designptrns/
13. What is the difference between single quotes and double quotes?
likelihood medium
Great answer at below link.
http://stackoverflow.com/questions/3446216/difference-between-single-quote-and-
double-quote-string-in-php
likelihood medium
Makes it so PHP does not output anything. Companies ask this because many large
frameworks wrap a bunch of code in ob_start() and ob_get_clean(). So understanding
how that function works is pretty important.
http://myphpsource.blogspot.com/2010/01/obstart-save-php-output-to-string-php.html
likelihood medium
'&' indicates a reference
http://schlueters.de/blog/archives/125-Do-not-use-PHP-references.html
likelihood medium
Final keywords indicates that the class or method cannot be extended.
http://php.net/manual/en/language.oop5.final.php
likelihood medium
No. You should understand what multiple inheritance is.
http://en.wikipedia.org/wiki/Multiple_inheritance
18. What are some magic methods in PHP, how might you use them?
likelihood medium
Magic methods are basically triggers that occur when particular events happen in your
coding. __GET, __SET are magic methods that are called (behind the seen) when you get
or set a class property.
http://php.net/manual/en/language.oop5.magic.php
likelihood medium
This is basically a trick questions. To understand how they are passed you need to
understand how objects are instantiated. Study the below link:
http://ca2.php.net/manual/en/language.oop5.references.php
likelihood medium
$$var sets the value of $var as a variable.
$day='monday';
$$day='first day of week';
echo $monday; //outputs 'first day of week'
17 Answers
active oldest votes
50 Admittedly, I stole this question from somewhere else (can't remember where I read it
accepted any more) but thought it was funny:
Q: What is T_PAAMAYIM_NEKUDOTAYIM?
A: Its the scope resolution operator (double colon)
An experienced PHP'er immediately knows what it means. Less experienced (and not
Hebrew) developers may want to read this.
$a = 3;
$b = doSomething( $a );
...what is the value of $a and $b after the function call and why?
A: $a is 4 and $b is 3. The former because $arg is passed by reference, the latter
because the return value of the function is a copy of (not a reference to) the initial value
of the argument.
OOP specific
class SomeClass
{
protected $_someMember;
A: Static methods don't have access to $this, because static methods can be executed
without instantiating a class.
Q: What is wrong with classes that predominantly define getters and setters, that map
straight to it's internal members, without actually having methods that execute
behaviour?
A: This might be a code smell since the object acts as an ennobled array, without much
other use.
Variables by reference
By default, function arguments are passed by value (so that if the value of the argument within the
function is changed, it does not get changed outside of the function). To allow a function to modify its
arguments, they must be passed by reference.
To have an argument to a function always passed by reference, prepend an ampersand (&) to the
argument name in the function definition.
<?php
function add_some_extra(&$string)
{
$string .= 'and something extra.';
}
$str = 'This is a string, ';
add_some_extra($str);
echo $str; // outputs 'This is a string, and something extra.'
?>
FizzBuzz is a very popular “test” used when interviewing programmers. It’s mostly used to filter
out people who can’t actually program. Now you may wonder why such a test would be
necessary, after all, why would somebody who can’t program apply for a programming job? The
unfortunate truth is, many people believe they can program (Some CompSci graduates for
example), when in reality they may have a strong theoretical knowledge but no practical
experience. There are also people who think it’s easy and they can pick it up as they go (I’ve had
a couple of these people come in when I was interviewing programmers to replace me an an old
job).
Here is how FizzBuzz works. The interviewer asks the interviewee to write a program in a
language of their choice (Or a specific language depending on the job, maybe even pseudo-
code). The program should count from 1 to X, X being a random number such as 20 or 100. For
each multiple of 3, the program should output “Fizz” instead of the number. For each multiple of
5, the program should output “Buzz” instead of the number. For each multiple of 3 AND 5 the
program should output “FizzBuzz” instead of the number. It’s a very trivial task for any
competent programmer, and the output should look like this:
1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz
16
17
Fizz
19
Buzz
How do you generate such output? Well here is a simple method written in PHP:
<?php
if ( PHP_SAPI != 'cli' ) {
echo '<pre>';
}
echo PHP_EOL;
}