Explore topic-wise InterviewSolutions in .

This section includes InterviewSolutions, each offering curated multiple-choice questions to sharpen your knowledge and support exam preparation. Choose a topic below to get started.

1.

__PHP_Incomplete_Class when do we get this? How to solve this problem?

Answer»

Sometime when we try to access session object we GET the object class as __PHP_Incomplete_Class.
This happens when we try to initialize the session before loading the class definitions for the object we are trying to save into the session.

  • To SAY it in simple, if class definitions are not defined, PHP CREATES incomplete objects of the class __PHP_Incomplete_Class.
  • To avoid __php_incomplete_class object session error, every class definition must be included or defined before STARTING the session
2.

How to expose private members when JSON encoding an object?

Answer»
  • JsonSerializable Interface: Objects implementing JsonSerializable can CUSTOMIZE their JSON representation when encoded with json_encode().
class Items implements \JsonSerializable { private $var; private $VAR1; private $var2; public function __construct() { // ... } public function jsonSerialize() { $vars = get_object_vars($this); RETURN $vars; } }
  • __toString: The toString() method allows a class to decide how it will react when it is treated LIKE as a string.
3.

How can you access class members as array indexes?

Answer»
  1. The indexes USED in an ArrayAccess object are not limited to strings and integers as they are for arrays: you can use any type for the index as long as you write your implementation to handle them. This fact is exploited by the SplObjectStorage class.
  2. ArrayAccess Interface: Interface to provide accessing objects as arrays class obj implements ArrayAccess {
private $CONTAINER = array(); public function __construct() { $this->container = array( "one" => 1, "two" => 2, "three" => 3, ); } public function offsetSet($offset, $value) { if (is_null($offset)) { $this->container[] = $value; } else { $this->container[$offset] = $value; } } public function offsetExists($offset) { return isset($this->container[$offset]); } public function offsetUnset($offset) { unset($this->container[$offset]); } public function offsetGet($offset) { return isset($this->container[$offset]) ? $this->container[$offset] : null; } } $obj = new obj; var_dump(isset($obj["two"])); var_dump($obj["two"]); unset($obj["two"]); var_dump(isset($obj["two"])); $obj["two"] = "A value"; var_dump($obj["two"]); $obj[] = 'Append 1'; $obj[] = 'Append 2'; $obj[] = 'Append 3'; print_r($obj); bool(true) int(2) bool(false) string(7) "A value" obj Object ( [container:obj:private] => Array ( [one] => 1 [three] => 3 [two] => A value [0]  => Append 1 [1]  => Append 2 [2]  => Append 3 ) )
4.

How to pass out of scope variables to a callback function? 

Answer»

Here is the code snippet for reference.

<?php $array = array (1, 3, 3, 8, 15); $my_val = 3; $filtered_data = array_filter($array, FUNCTION ($ELEMENT) use ($my_val) { return ($element != $my_val); } ); print_r($filtered_data); ?>
5.

What are promises?

Answer»

Promises becomes very important when it comes to asynchronous COMMUNICATION and it also provides effective ways to manage resources.

  1. A PROMISE is an object that may produce a single value sometime time in the future: either a resolved value, or a reason that it’s not resolved (e.g., a network error OCCURRED). A promise may be in one of 3 possible states: fulfilled, rejected, or pending. Promise users can attach callbacks to handle the fulfilled value or the reason for rejection.
  2. It started with JS but has been implemented in variety of technologies including PHP.
  3. Some libraries we can USE to implement promises in PHP:
  4. https://github.com/guzzle/promises
  5. https://github.com/reactphp/promise
6.

What are generators?

Answer»

Generators provide an easy way to implement simple iterators without the overhead or complexity of implementing a class that implements the Iterator interface. A generator allows you to write code that uses FOREACH to iterate over a set of data without NEEDING to BUILD an array in memory, which may CAUSE you to exceed a memory limit, or require a considerable amount of processing time to generate. Instead, you can write a generator function, which is the same as a normal function, except that instead of returning once, a generator can yield as many times as it needs to in order to provide the values to be iterated over.

<?php function nums() { echo "The generator has startedn"; for ($i = 0; $i < 5; ++$i) { yield $i; echo "Yielded $in"; } echo "The generator has endedn"; } foreach (nums() as $v);
7.

What is a resource? Which functions return/create resource?

Answer»

A resource is a special VARIABLE, holding a reference to an external resource. Resources are CREATED and used by special functions. The following is a list of functions which create, USE or destroy PHP resources. The function is_resource() can be used to determine if a variable is a resource and get_resource_type() will return the TYPE of resource it is. HTTPS://www.php.net/manual/en/resource.php

8.

Does PHP support event loop? If yes give some example.

Answer»
  • Event Loop is a concept from Javascript. In a single threaded execution, the CODE is waiting for the activity to GET over before moving ahead. Event Loop helps us utilize the waiting period to EXECUTE code.
  • PHP supports Event loop. There are multiple libraries which HELP us USE event loop in our project
    • https://github.com/reactphp
    • https://github.com/icicleio
    • https://github.com/asyncphp/doorman
9.

What is OPcache?

Answer»

Performance is a very important aspect considered in any language at RUNTIME. In ORDER to improve the performance of the PHP runtime engine, OPcache can help in a significant way.

  1. OPcache improves PHP performance by STORING precompiled script bytecode in shared memory, thereby removing the need for PHP to load and parse scripts on each request.
  2. OPcache is bundled with PHP 5.5 and higher. OPcache is more closely bound to PHP itself than other bytecode cache engines like APC.
  3. The whole cache engine works in the background and is transparent to a visitor or a WEB developer. In order to check its status, you may use ONE of the two functions that provide such information: opcache_get_configuration() and opcache_get_status()
10.

How does the method overriding work with Traits?

Answer»

An inherited member from a base class is overridden by a member inserted by a Trait. The PRECEDENCE order is that members from the current class OVERRIDE Trait METHODS, which in turn override inherited methods. An inherited method from a base class is overridden by the method inserted into MyHelloWorld from the SayWorld Trait.

The behaviour is the same for the methods defined in the MyHelloWorld class. The precedence order is that methods from the current class override Trait methods, which in turn override methods from the base class.

trait A { function calc($v) { return $v+1; } } class MyClass { use A { calc as protected traitcalc; } function calc($v) { $v++; return $this-&GT;traitcalc($v); } }
11.

What are traits? What problem do they solve?

Answer»

Traits are a mechanism for code reuse in single inheritance languages such as PHP. A Trait is intended to reduce some limitations of single inheritance by enabling a developer to reuse sets of methods freely in several independent classes living in different class hierarchies.

The semantics of the combination of Traits and classes are defined in a way that reduces COMPLEXITY and AVOIDS the typical problems associated with multiple inheritance and Mixins.

A Trait is similar to a class, but only intended to group functionality in a fine-grained and consistent way. It is not possible to instantiate a Trait on its own. It is an addition to traditional inheritance and ENABLES HORIZONTAL composition of behaviour; that is, the application of class members without requiring inheritance.

<?php trait Hello { function sayHello() { echo "Hello"; } } trait World { function sayWorld() { echo "World"; } } class MyWorld { use Hello, World; } $world = NEW MyWorld(); echo $world->sayHello() . " " . $world->sayWorld(); //Hello World
12.

What are array_map, array_reduce and array_walk?

Answer»

Here are the use-cases for array_map, array_reduce and array_walk.

  1. Array_map: Applies the callback to the elements of the given arrays
  2. Array_reduce: ITERATIVELY reduce the array to a single VALUE using a callback function
  3. Array_walk: Apply a user supplied function to every member of an array
<?php $originalarray1 = array(2.4, 2.6, 3.5); $originalarray2 = array(2.4, 2.6, 3.5); print_r(array_map('floor', $originalarray1)); // $originalarray1 stays the same // changes $originalarray2 array_walk($originalarray2, function (&$v, $k) { $v = floor($v); }); print_r($originalarray2); // this is a more proper use of array_walk array_walk($originalarray1, function ($v, $k) { ECHO "$k => $v", "\n"; }); //  array_map accepts several arrays print_r( array_map(function ($a, $b) { return $a * $b; }, $originalarray1, $originalarray2) ); //  select only elements that are > 2.5 print_r( array_filter($originalarray1, function ($a) { return $a > 2.5; }) ); ?> Array ( [0]  => 2 [1]  => 2 [2]  => 3 ) Array ( [0]  => 2 [1]  => 2 [2]  => 3 ) 0 => 2.4 1 => 2.6 2 => 3.5 Array ( [0]  => 4.8 [1]  => 5.2 [2]  => 10.5 ) Array ( [1]  => 2.6 [2]  => 3.5 )
13.

What are the various ways to execute PHP with Apache/Nginx? 

Answer»

WEB Servers themselves cannot understand and parse PHP files, the EXTERNAL programs do it for them. There are many ways how you can do this, both with its PROS and cons. Various ways:

  1. Mod_php: means PHP, as an Apache module
  2. FastCGI: a PHP process is launched by Apache, and it is that PHP process that interprets PHP code -- not Apache itself
  3. PHP-FPM: PHP-FPM (FastCGI Process MANAGER) is an ALTERNATIVE PHP FastCGI implementation with some additional features useful for sites of any size, especially busier sites
14.

Does PHP support WebSockets? If yes give some examples.

Answer»

In order to reduce RTT ( Round trip time ), websockets becomes handy if you are thinking about performance.

  1. WebSocket is a PROTOCOL for CREATING a FAST two-way channel between a web browserand a server. WebSocket overcomes limitations with HTTP to allow for low latency communications between a user and a web service
  2. PHP supports WebSockets and the following PROJECTS help us use them in our projects:

    i.   https://socketo.me 
15.

How to do request profiling in PHP?

Answer»

Xdebug is an extension for PHPto assist with debugging and development. It contains a single step debuggerto USE with IDEs; it upgrades PHP's var_dump() function; it adds stack tracesfor Notices, Warnings, Errors and Exceptions; it features functionality for recording every function call and variable assignmentto disk; it contains a profiler; and it provides code coveragefunctionality for use with PHPUnit.

Xhprof: Xhprof was created by Facebook and includes a basic UI for reviewing PHP profiler data. It aims to have a minimum impact on execution times and REQUIRES relatively little space to store a trace. Thus, you can run it live WITHOUT a noticeable impact on users and without EXHAUSTING the memory.

16.

What is PHP-FPM?

Answer»

PHP-FPM (FastCGI Process Manager) is an alternative PHP FastCGI implementation with some additional features useful for sites of any size, especially BUSIER sites. These features include:

  • Adaptive process spawning (NEW!)
  • Basic STATISTICS (ala Apache's mod_status) (NEW!)
  • Advanced process management with graceful stop/start
  • Ability to start workers with different uid/gid/chroot/environment and different php.ini (replaces safe_mode)
  • STDOUT & stderr logging
  • Emergency restart in case of accidental opcode cache destruction
  • Accelerated upload support
  • Support for a "slowlog"
  • ENHANCEMENTS to FastCGI, such as fastcgi_finish_request() - a special function to finish request & flush all data while continuing to do something time-consuming (video converting, stats processing, etc.)
17.

How to do syntax checking using PHP?

Answer»

Here are some steps you can follow to CHECK the syntax of PHP. Ensure PHP CLI is installed on your MACHINE. Browse to the relevant folder where the code is. Run the COMMAND php -L testfile.phpvia command line.

This will detect any syntax ERRORS in the code and display on a terminal

18.

What is PSR?

Answer»

PSR Stands for PHP Standard Recommendations. These are some GUIDELINES created by the community to bring a standard to projects/Libraries and have a common language which EVERYONE can SPEAK and understand.

  • Basic coding standard
  • Coding style. Guide
  • Logger interface
  • Autoloading standard
  • Caching interface
  • HTTP MESSAGE interface
  • Container interface
  • Hypermedia links
  • Http Handlers
  • Simple cache
  • HTTP Factories
  • HTTP CLIENT
19.

What is a composer?

Answer»

Composer is a tool for dependency management in PHP. It allows you to DECLARE the LIBRARIES your project depends on and it will manage (install/update) them for you. It is a dependency manager

  • It enables you to declare the libraries you depend on.
  • Finds out which versions of which packages can and need to be installed, and installs them (meaning it downloads them into your project).
    • composer INIT - to launch a wizard
    • composer require - to add a dependency, also creates a composer.json to manage dependencies
    • composer.lock - this file ensures that everyone in the project uses the same version of the packages by not allowing newer versions to be downloaded
20.

What is a namespace?

Answer»

Namespaces are a way of encapsulating items. In the PHP world, namespaces are designed to solve two problems that AUTHORS of libraries and applications encounter when creating reusable code elements such as classes or functions:

  1.    Name collisions between code you create, and internal PHP classes/functions/constants or third-party classes/functions/constants.
  2.    Ability to alias (or shorten) Extra_Long_Names designed to alleviate the first problem, improving readability of source code.

PHP Namespaces provide a way in which to GROUP related classes, interfaces, functions and constants.

In SIMPLE TERMS, think of a namespace as a person's surname. If there are two people named "James" you can use their surnames to tell them apart.

namespace MyProject;

function output() { # Output HTML page echo 'HTML!'; } namespace RSSLibrary; function output(){ #  Output RSS feed echo 'RSS!'; }

Later when we want to use the different functions, we'd use:

\MyProject\output(); \RSSLibrary\output();

Or we can DECLARE that we're in one of the namespaces and then we can just call that namespace's output():

namespace MyProject;

output(); # Output HTML page \RSSLibrary\output();
21.

What are the limitation in SilverStripe?

Answer»
22.

List some plugins in SilverStripe?

Answer»
23.

How to install themes in SilverStripe?

Answer»
24.

How to install SilverStripe modules?

Answer»
25.

What is the latest version of SilverStripe?

Answer» 7. EXPLAIN the NEW FEATURES of SilverStripe 4?
26.

Explain the SilverStripe vs. WordPress?

Answer»
27.

Is SilverStripe is an open source?

Answer»
28.

How to install SilverStripe on our local system?

Answer»
29.

Explain the advantages of SilverStripe?

Answer»
30.

What is SilverStripe and why it is used?

Answer»

It is a FREE and open-source CMS and FRAMEWORK for creating websites and web applications. It provides an ADMIN panel that enables users to make changes to PARTS of the WEBSITE.

31.

How to use "404 Not Found" in Slim Framework?

Answer»
32.

How to upload files in Slim Framework?

Answer»
33.

What is CORS and how it is enabled in Slim Framework?

Answer»

CORS or Cross-Origin RESOURCE Sharing is a middleware that implements resource sharing across the origin. In Slim application, CORS is implemented through Access-Control-Allow-Origin header. The best WAY to enable CORS is by USING the cors-middleware PACKAGE.

34.

How to get IP address of client machine in Slim Framework?

Answer»

Our most EXTENSIVE Slim framework interview questions and answers can help DEVELOPERS CRACK any job interview.

$REQUEST-&GT;getAttribute('ip_address').
OR
$requestIP = $request->getServerParam('REMOTE_ADDR');

35.

How to create routes in Slim Framework?

Answer» 16. What Request METHOD is AVAILABLE in Slim Framework? Explain

Every HTTP request in the Slim Framework has a request method ASSIGNED. Here are some of the request methods:

  • GET
  • POST
  • PUT
  • DELETE
  • HEAD
  • PATCH
  • OPTIONS
36.

What is Route callbacks and explain its arguments?

Answer»

Each routing METHOD in Slim Framework will accept a callback routine as the FINAL argument. The last CASE may be any PHP callable.

By default, the framework allows three arguments - Request, RESPONSE, arguments.

An argument is a function that specifies the actions to be taken when a route is matched to a request. It includes values for the existing route’s specific PLACEHOLDERS.

37.

How to define a middleware in Slim Framework?

Answer»
38.

What is Dependency Injection in Slim Framework?

Answer»

In Slim FRAMEWORK, dependency injection is a container for preparing, managing, and injecting application DEPENDENCIES.

12. How to set and get a cookie in Slim Framework?

Setting a cookie in Slim Framework will REQUIRE a key, value, and specific time to allow the cookie to be present.

Example

// With all parameters

$app->setCookie(
   $name,
   $value,
   $expiresAt,
   $path,
   $DOMAIN,
   $SECURE,
   $httponly
);


// To set Cookie
$app->setCookie('bestinterviewquestion', 'bar', '2 days');

// To get Cookie
$app = new \Slim\Slim();
$foo = $app->getCookie('bestinterviewquestion');

39.

What do you mean by middleware in Slim Framework?

Answer»

A middleware is a kind of callable that accepts three types of arguments- PSR7 request object, a PSR7 RESPONSE object, and next middleware. A middleware can do all types of functions with objects. However, a middleware MUST INITIATE next middleware and CLEAR Response and Request objects as arguments.

If you are PREPARING for Slim interview, you can READ our slim framework tutorial for in-depth knowledge.

40.

What is Hook in Slim Framework and how it is used?

Answer»

In the Slim Framework, a hook is used to register a callback. Identified by string names, a hook is an instance at which the callables will get invoked as PER the PRIORITY LIST assigned. It is POSSIBLE to attach multiple callables to a single hook by using the hook() METHOD.

41.

What are the steps to upgrade from version 2 to version 3 in Slim Framework?

Answer»
42.

What are the System Requirements to install Slim Framework?

Answer»
43.

What are the features of Slim Framework?

Answer»

This information has been ASKED quite a few times recently in Slim FRAMEWORK interview questions.

Features of Slim Framework
  • Includes great routes - Route middleware, Route REDIRECT, and Standard HTTP methods.
  • Easy to solve and fix the errors
  • AES-256 ENCRYPTION secures the data and stores in cookies
  • Possible to render external PHP FILES using template rendering
44.

How to install Slim Framework with composer?

Answer»

COMPOSER REQUIRE slim/slim "^3.0"

45.

What is the latest version of Slim Framework?

Answer»

SLIM 3.12.0 RELEASED on 15 JAN 2019

46.

How to Slim framework different from other frameworks like Zend, Laravel, Symfony? Explain

Answer»
S.noLaravel, Symfony, and ZendSlim
1.Full-stack frameworksMicro framework
2.Consist of individual components that do different tasks necessary for complex WEB apps.A single component library that ADDRESSES the CORE of web apps.
3.Come with overheadMinimal overhead
47.

What is Slim framework and why it is used?

Answer»

A PHP micro-framework, Slim helps the developers write easy yet powerful APIs and web applications. This framework provides a fast and robust router that can map route callbacks to various HTTP requests and URIs.It supports PSR-7 HTTP MESSAGE implementation which allows the developers to assess and manipulate HTTP message METHOD, status, headers, URI, body, and cookies.

Uses of Slim Framework
  • A QUICK way to write powerful APIs and web applications
  • Allows you to map functions with URLs and methods
  • Allow you to modify requests and responses.
  • Developers have control over dependencies using DEPENDENCY Injection
2. Is Slim framework similar to Silex and how do they differ?

Slim and Silex are different because Slim is a micro framework, while Silex is a full-stack framework.

Slim and Silex are similar because they both help developers build web applications with simple tools for receiving a request and delivering a response.

48.

Explain the Session methods in FuelPHP?

Answer»
  • CREATE ()- Used for creating a NEW session.
  • Set ()- Used for assigning a session variable.
  • Destroy ()- Destroying the existing session is the main task of this method.
  • Get ()- it GETS the sessions variable.
  • Delete ()- It DELETES the STORED variable which has been retrieved from the sessions.
49.

Explain the types of controllers in FuelPHP?

Answer»
50.

How to check an Ajax request on the server?

Answer»

Checking an Ajax request on the server is a task which can be DONE with the HELP of input CLASS method. If there has been an Ajax request on the server, then the function, Input::is_ajax will return TRUE, and in the otherwise case, it will return false.

Example

if (Input::is_ajax()) {
    // Ajax request
} else {
    // Normal request
}