Now that you have made a quality JD, it can still be tricky to evaluate the skills of your applicants when you hire Laravel developers. To help you with that, we have created a pool of questions that a good Web developer should be comfortable with.
It is important to note that the ability to answer these questions doesn't imply that you have a top quality candidate. But it definitely is a big step in that direction.
To help you navigate through these questions, we’ve categorized the interview questions in 3 parts:
A. Basic concepts: Includes all basic concepts used across languages.This will give you an understanding of how strong their programming foundation is.
B. Advanced concepts: Includes all concepts that someone with higher expertise should know.
C. DS/Algorithm questions: To test the logical capability of the candidate.
A. Basic concepts
What is the purpose of $GLOBALS & $_SERVER variables in PHP?
$GLOBALS & $_SERVER variables are PHP superglobals. Superglobals are specially-defined array variables used to get or store information from the different pages of an application. These variables can be accessed at all times regardless of scope from any function, class, or file.
PHP has 3 variable scopes - local, global, and static.
- Local - Any variable defined inside a function has a local scope and can only be accessed inside the function.
- Global - A variable declared outside the function has a global scope and can be accessed outside the function, But, using the 'global' keyword, you can access any global variable inside a function.
- Static - PHP deletes all variables after the function is executed. The variable must be declared static if its value needs to be used after function execution.
Example: of accessing a global variable inside a function:
$x = 10; //global scope
$y = 12;
function add() {
global $x, $y;
$y = $x + $y;
}
addt();
echo $y; // outputs 22
Another way of doing the same would be using the $GLOBALS superglobal.
$GLOBALS is used to access global variables from anywhere in the script. PHP stores all the global variables in an array called $GLOBALS[]. To access a particular global variable you must pass the variable name as an index to the array. ($GLOBALS[index~name])
Considering the same example:
$x = 10;
$y = 12;
function multiply(){
$GLOBALS['z'] = $GLOBALS['x'] * $GLOBALS['y'];
}
multiply();
echo $z;
In the code above, $x and $y are global variables holding values 10 and 12 respectively. A function multiply() performs a multiplication operation on the two global variables using the $GLOBALS[] to output 120.
The $_SERVER superglobal stores information about the headers, paths, and script locations.
Some important elements that the $_SERVER variable holds are:
1. $_SERVER['PHP_SELF']- returns the filename of the current script
2. $_SERVER['GATEWAY_INTERFACE']- returns the CGI version
3. $_SERVER['SERVER_ADDR']- returns the host server’s IP address
4. $_SERVER['SERVER_NAME']- returns the host server name
5. $_SERVER['REQUEST_METHOD']- returns the request method used. Example- POST or GET.
6. $_SERVER['REQUEST_TIME']- returns the request start time in timestamp
7. $_SERVER['HTTP_HOST']- returns the host header of the current request
8. $_SERVER['SCRIPT_NAME']- returns the path of the current script
9. $_SERVER['SERVER_PORT']- returns the port being used for communication
10. $_SERVER['REMOTE_ADDR']- returns the IP address of the user viewing the current page
Example:
echo $_SERVER['SERVER_NAME'];
echo $_SERVER['SCRIPT_NAME'];
The output for the above code snippet is :
localhost
/demodoc/demo_global_server.php
What are the methods used to collect form data after the form is submitted to the server in PHP? Can you submit a form without a submit button? If yes, give 2 examples and also mention how would you verify if the form is successfully submitted?
The GET and POST methods are used to collect form data after the form is submitted to the server. They’re both treated as superglobals and hence are accessible at all times($_GET & $_POST). Both, GET and POST create an array that holds key/value pairs, where the key is the name of the form control and value is the input data from the user.
The basic difference between the two is that the $_GET variables are passed to the current script via URL parameters and $_POST variables are passed via the HTTP POST method.
The GET method is not advised when you need to send important information like a password because the information sent via the GET method is visible to everyone as opposed to that of the POST method that goes via the headers of the HTTP POST method and remains invisible to others.
The POST method has no limits on the characters passed but the GET method is limited to approximately 2000 characters only.
Here’s an example of a simple form using the post method:
When the submit button is clicked, the data inside name and email input fields are sent via the HTTP POST method to a PHP file.
Hi <?php echo $_POST["name"]; ?>Your email address is: <?php echo $_POST["email"]; >
The output of the above snippet will be:
Welcome Sam
Your email address is: [email protected]
To achieve the same with $_GET, change the method to ‘get’:
<form action="reg.php" method="get">
Name: <input type="text" name="name">
Email: <input type="text" name="email">
#reg.php
Hi <?php echo $_GET["name"]; ?>
Your email address is <?php echo $_GET["email"]; ?>
The output then be:
Hi Sam
Your email address is [email protected].
And the URL will be
localhost/reg.php?name=Sam&email=sam%robustplus.com
Yes, a form can be submitted without the submit button. The most commonly used ways of doing it are:
A. Submit a form by clicking on a link using the onclick() method:
<a href="#" onclick="document.getElementById('submit').submit(); >
where 'submit' is the form ID.
B. Submit by selecting an option from the drop-down menu on change:
$('#theme').change(function(){
$('form').submit();
});
where ‘theme’ is the id of <select>
The
isset() method is used to check if the form has been successfully submitted.
if (isset($_POST['submit'])) {
echo "Successful submission";
}
where ‘submit’ is the button name.
B. Advanced concepts
What are traits in PHP? What are the keywords used to declare and use traits? Explain with an example.
PHP doesn’t support multiple inheritances. The ‘extends’ keyword is used to perform a single class inheritance. Traits were introduced in PHP 5.4 to provide multiple inheritances. In a nutshell, traits are used to declare methods that can be used in multiple classes. These methods also include abstract methods with any access modifier- public, private, or protected.
Traits are similar to classes but they are used for grouping methods consistently and unlike a class, they can’t be instantiated on their own.
The 'trait’ keyword is used to declare traits:
trait Trait1{
//code
}
And the use’ keyword is used to use a trait in a class:
class MyClass {
use Trait1;
}
Example:
Let’s create a library.php file and create a class library
class Library{
public function student(){
echo "I am student A";
}
}
Now, let’s create another file index.php and create a class book and extend it to Library
require_once 'Library.php';
class Book extends Library{
}
$obj = new Book;
$obj->student();
When we run index.php it will output ‘I am student A’ but what if Book comes with a new feature of having an ebook version?
Let’s create a new file for ebook.php
class Ebook{
public function version(){
echo '1.0’;
}
}
Now, if I want to inherit Book in the index.php file- I can’t do it because it already extends Library.
This is where I can use traits. All I have to do is convert the class to a trait like:
trait Ebook{
public function version(){
echo '1.0’;
}
}
Now to make the methods in Ebook available in Index- I need to add ebook in index.php>
require_once ‘Library.php';
require_once ‘Ebook.php';
class Book extends Library{
use Ebook;
}
$obj = new Book;
// now I can use methods inside trait Ebook
$obj->version();
//and methods from library
$obj->student();
I can also use 2 traits together. Let's assume I have another trait Price with a function range.
Index.php:
require_once ‘Library.php';
require_once ‘Ebook.php';
require_once ‘Price.php';
class Book extends Library{
use Ebook, Price;
}
$obj = new Book;
// now I can use methods inside trait Price
$obj->range();
// now I can use methods inside trait Ebook
$obj->version();
// and method from Library
$obj->student();
If you have 2 traits with the same method name range. PHP will throw a fatal error but it can be fixed using the ‘insteadof’ keyword.
Ebook::range insteadof Price;
//Or pass it as an alias:
Price::range as Prange;
How are objects created in PHP? Why and how are the keywords $this and $instancof used? Explain with examples.
Objects are individual instances of the data structure defined by a class. We can make multiple objects from a class. Each object inherits all the properties and methods defined in the class but has different property values.
Objects of a class are created using the new keyword.
Example:
class Colors{}
$yellow = new Colors;
$orange = new Colors;
Objects are also called instances. Once you’ve created the objects, you can use parent class methods on them.
class Colors{
function set_name($name) {
$this->name = $name;
}
function get_name() {
return $this->name;
}
}
$yellow = new Colors;
$yellow>set_name('light');
echo $yellow>get_name();
The $this keyword maps to the current object and allows you to make changes to object values inside the method.
Example:
class Colors{ public $shade; }
$yellow = new Colors;
If I want to change the value of $shade, I can create a method set_shade() and use the $this keyword inside the class like:
class Colors{
public $shade;
function set_shade($name) {
$this->shade = $shade;
}
}
$yellow = new Colors();
$yellow>set_shade("Light Yellow");
Or I can do it outside the class directly:
class Colors{
public $shade;
}
$yellow = new Colors();
$yellow>shade = "Light Yellow";
The $instanceof keyword is used to check if an object belongs to a specific class.
Example:
$yellow = new Colors();
var_dump($yellow instanceof Colors);
The output will be bool(true).
What are generators and how are they different from normal functions? How do they work in PHP? Can you send values to the generator? If yes, how? Explain with an example.
Generators were introduced in PHP 5.5 and while they look like functions, they act like iterators. Generators nullify the complexity of implementing a class that implements the Iterator interface. They are similar to functions except that they don’t return a value but yield as many values as needed.
Generators return an object that can be iterated over. This is an object of the internal Generator class that implements the Iterator interface. Generators use the keyword ‘yield’ instead of ‘return’. Unlike ‘return’, ‘yield’ does not remove the function from the stack- it rather saves its state so that the execution can be continued when it is called again. Although, the ‘return’ keyword can be used to terminate the execution. The main purpose of a generator is to save memory and speed up the execution.
Example:
function read_file($filename) {
$file = fopen($filename, 'r');
while (($line = fgets($file)) !== false) {
yield $line;
}
fclose($file);
}
foreach (read_file(‘file_name’) as $line) {
}
In the above code, the generator function yields the lines of the file passed as and when needed. Each time a call is made, the generator resumes from where it left off. After all the lines are read, the generator terminates and the loop ends.
Yes, the send() method is used to send values or commands to the generator. This method is used on the result of the yield expression. For example, telling the generator to stop the execution.
Example:
function numbers() {
for ($i = 0; $i < 6; ++$i) {
$cmd = (yield $i);
if ($cmd == 'stop') {
return; // exit the generator
}
}
}
$generator = numbers();
foreach ($generator as $a) {
if ($a == 4) {
$generator->send('stop');
}
echo "{$a}";
}
In the above code, the generator will iterate till a is 4, output- 0 1 2 3 4 and terminate the execution.
What is composition over inheritance? Where does PHP (as a language) implement this?
Composition over inheritance in OOP is the principle that classes should achieve polymorphism by their composition (reusing code) rather than inheritance from a base or parent class.
In OOP, there are two ways of achieving polymorphism- inheritance & composition.
Inheritance is based on a parent-child relationship a.k.a the ‘Is-a’ relationship. It bases one class/object on another class/object retaining similar implementation. In simpler words, a subclass inherits all methods of its superclass. For example, a subclass ‘Cat’ inherits all traits of its superclass ‘Animal’.
Composition, on the other hand, is the mechanism to reuse code across classes. The superclass is connected to the subclasses via a ‘has-a’ relationship. For example, a class ‘Car’ can be composed of an ‘Engine’ class as well as any other components to achieve a holistic functioning of the ‘Car’ class.
While Composition is dynamic binding (run-time binding), Inheritance is static binding (-binding)
To explain with an example composition over inheritance,
class Vehicle
{
public function move()
{
echo "Move the car";
}
}
class Car extends Vehicle
{
public function accelarate()
{
move();
}
$car = new Car();
$car->accelerate();
}
In the above code snippet, there is a tight coupling(inheritance) between the classes- Vehicle and Car. Even the slightest change in the move() function in Vehicle class will cause the class Car to break. This can be solved using composition:
class Vehicle
{
public function move()
{
echo "Move the car";
}
}
class Car
{
private $vehicle;
public function __construct(Vehicle $vehicle)
{
$this->vehicle = $vehicle;
}
public function accelarate()
{
$this->vehicle->move();
}
}
$vehicle = new Vehicle();
$car = new Car($vehicle);
$car->accelarate();
In this code snippet, passing the reference of class Vehicle into class Car’s constructor using dependency injection removes the tight coupling. The superclass and subclass are now independent of each other.
What is the factory pattern? How would you implement it in PHP?
Design patterns in PHP act like blueprints that can be customized to solve a recurring software design problem. These patterns provide well tested, proven development/design paradigms that help to speed up the development process. Using design patterns, you can make your code more reusable, flexible, and maintainable.
PHP has 3 design patterns-
1. Creational patterns: These patterns are used to construct objects that can be decoupled from their implementing system.
2. Structural patterns: These patterns are used to form object structures between many different objects
3. Behavioral patterns: These patterns are used to manage relationships, algorithms, and responsibilities between objects.
The Factory design pattern is one of the most used creational design patterns. It solves the problem of creating product objects without specifying their concrete class by maintaining a dedicated class responsible only for making objects. It is recommended to use the factory pattern when the subclass of an object instantiated can vary.
Example:
class Digital
{
private $mobileMake;
private $mobileModel;
public function __construct($make, $model)
{
$this->mobileMake = $make;
$this->mobileModel = $model;
}
public function getMakeAndModel()
{
return $this->mobileMake . ' ' . $this->mobileModel;
}
}
class DigitalFactory
{
public static function create($make, $model)
{
return new Digital($make, $model);
}
}
$honor = DigitalFactory::create('Honor', '10 Lite');
print_r($honor>getMakeAndModel()); // outputs "Honor 10 Lite"
This code uses a 'DigitalFactory' to create a Digital object. The 2 benefits of doing this are:
1. You can change, rename, or replace the Digital class whenever you need to- all you have to do is modify the code in the 'DigitalFactory', instead of every instance of the class in your project.
2. Instead of creating a new instance every time you want to create an object- you can simply do all the work in the factory and reuse it.
C. Data Structure/ Algorithm
What will the output of the following code be?
$x = 10;
$y = 5;
$z = 3;
if ($x / $y / $z)
print "hi";
else
print "hello";
a) hi
b) hello
c) error
d) no output
The answer is A because the floating-point division in PHP returns a non zero value = 0.66 which evaluates to
true and outputs ‘hi’.
What will the output of the following code be?
$x = 2
$y = 4
$z = 6
if($z > $y > $x) {
echo “true”;
}else{
echo “false”;
}
The answer is False. It may look like the output can be true because 6 > 4 > 2 is true but PHP evaluates
$z > $y first which returns a boolean value of 1 or true. This value (true or 1) is compared to the next integer
in the chain, bool(1) > $z, which will result in NULL and echo “false.”