You can check all 82 PHP interview questions here π https://devinterview.io/dev/php-interview-questions
PHP allows the user to modify some of its settings mentioned in php.ini using ini_set(). This function requires two string arguments. First one is the name of the setting to be modified and the second one is the new value to be assigned to it.
Given line of code will enable the display_error setting for the script if itβs disabled.
ini_set('display_errors', '1');
We need to put the above statement, at the top of the script so that, the setting remains enabled till the end. Also, the values set via ini_set() are applicable, only to the current script. Thereafter, PHP will start using the original values from php.ini.
- The operator
==
casts between two different types if they are different - The
===
operator performs a 'typesafe comparison'
That means that it will only return true if both operands have the same type and the same value.
1 === 1: true
1 == 1: true
1 === "1": false // 1 is an integer, "1" is a string
1 == "1": true // "1" gets casted to an integer, which is 1
"foo" === "foo": true // both operands are strings and have the same value
$GLOBALS
is associative array including references to all variables which are currently defined in the global scope of the script.
Consider:
Array ( [0] => Hello [1] => world [2] => It's [3] => a [4] => beautiful [5] => day)
The keys of an indexed array are 0, 1, 2 etc. (the index values) and values are "Hello", "world", "It's", "beautiful", "day".
The PHP configuration file, php.ini, is the final and most immediate way to affect PHP's functionality. The php.ini file is read each time PHP is initialized.in other words, whenever httpd is restarted for the module version or with each script execution for the CGI version.
To be able to pass a variable by reference, we use an ampersand in front of it, as follows:
$var1 = &$var2
PHP supports only single inheritance; it means that a class can be extended from only one single class using the keyword 'extended'.
stdClass
is just a generic 'empty' class that's used when casting other types to objects. stdClass
is not the base class for objects in PHP. This can be demonstrated fairly easily:
class Foo{}
$foo = new Foo();
echo ($foo instanceof stdClass)?'Y':'N'; // outputs 'N'
It is useful for anonymous objects, dynamic properties, etc.
An easy way to consider the StdClass
is as an alternative to associative array. See this example below that shows how json_decode()
allows to get an StdClass instance or an associative array.
Also but not shown in this example, SoapClient::__soapCall
returns an StdClass
instance.
//Example with StdClass $json = '{ "foo": "bar", "number": 42 }'; $stdInstance = json_decode($json);
echo $stdInstance - > foo.PHP_EOL; //"bar" echo $stdInstance - > number.PHP_EOL; //42
//Example with associative array $array = json_decode($json, true);
echo $array['foo'].PHP_EOL; //"bar" echo $array['number'].PHP_EOL; //42
PDO stands for PHP Data Object.
It is a set of PHP extensions that provide a core PDO class and database, specific drivers. It provides a vendor-neutral, lightweight, data-access abstraction layer. Thus, no matter what database we use, the function to issue queries and fetch data will be same. It focuses on data access abstraction rather than database abstraction.
empty
is more or less shorthand for!isset($foo) || !$foo
, and !empty
is analogous to isset($foo) && $foo
. empty
is the same as !$foo
, but doesn't throw warnings if the variable doesn't exist. That's the main point of this function: do a boolean comparison without worrying about the variable being set.
echo
and print
are more or less the same. They are both used to output data to the screen.
The differences are:
- 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 faster than print.
!=
means inequality (TRUE if $a is not equal to $b) and !==
means non-identity (TRUE if $a is not identical to $b).
It's for declaring class member variables in PHP4, and is no longer needed. It will work in PHP5, but will raise an E_STRICT warning in PHP from version 5.0.0 up to version 5.1.2, as of when it was deprecated. Since PHP 5.3, var has been un-deprecated and is a synonym for 'public'.
Consider:
class foo {
var $x = 'y'; // or you can use public like...
public $x = 'y'; //this is also a class member variables.
function bar() {
}
}
In associative arrays, we can use named keys that you assign to them. There are two ways to create an associative array:
// first way -
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");`
// another method - $age['Peter'] = "35"; //Peter, Ben & Joe are keys $age['Ben'] = "37"; //35, 37 & 43 are values $age['Joe'] = "43";
There's no difference - they are the same. The only advantage of choosing die()
over exit()
, might be the time you spare on typing an extra letter.
- A
notice
is a non-critical error saying something went wrong in execution, something minor like an undefined variable. - A
warning
is given when a more critical error like if an include() command went to retrieve a non-existent file. In both this and the error above, the script would continue. - A
fatal error
would terminate the code. Failure to satisfy a require() would generate this type of error, for example.
PHP doesn't have native Enumerations. Depending upon use case, I would normally use something simple like the following:
abstract class DaysOfWeek { const Sunday = 0; const Monday = 1; // etc. }
$today = DaysOfWeek::Sunday;
There is a native extension, too. SplEnum gives the ability to emulate and create enumeration objects natively in PHP.
When an exception is thrown, code following the statement will not be executed, and PHP will attempt to find the first matching catch block. If an exception is not caught, a PHP Fatal Error will be issued with an "Uncaught Exception". An exception can be thrown, and caught within PHP.
To handle exceptions, code may be surrounded in a try
block.
Each try must have at least one corresponding catch
block. Multiple catch blocks can be used to catch different classes of exceptions.
Exceptions can be thrown (or re-thrown) within a catch block.
Consider:
try {
print "this is our try block n";
throw new Exception();
} catch (Exception $e) {
print "something went wrong, caught yah! n";
} finally {
print "this part is always executed n";
}
The fundamental difference between const
vs define
is that const
defines constants at compile time, whereas define
defines them at run time.
const FOO = 'BAR'; define('FOO', 'BAR');
// but if (...) { const FOO = 'BAR'; // Invalid } if (...) { define('FOO', 'BAR'); // Valid }
Also until PHP 5.3, const
could not be used in the global scope. You could only use this from within a class. This should be used when you want to set some kind of constant option or setting that pertains to that class. Or maybe you want to create some kind of enum. An example of good const
usage is to get rid of magic numbers.
Define
can be used for the same purpose, but it can only be used in the global scope. It should only be used for global settings that affect the entire application.
Unless you need any type of conditional or expressional definition, use consts
instead of define()
- simply for the sake of readability!
array_key_exists
will tell you if a key exists in an array and complains when$a
does not exist.isset
will only returntrue
if the key/variable exists and is notnull
.isset
doesn't complain when$a
does not exist.
Consider:
$a = array('key1' => 'Foo Bar', 'key2' => null);
isset($a['key1']); // true array_key_exists('key1', $a); // true
isset($a['key2']); // false array_key_exists('key2', $a); // true
No, you cannot extend a Final
defined class. A Final
class or method declaration prevents child class or method overriding.
PSRs are PHP Standards Recommendations that aim at standardising common aspects of PHP Development. An example of a PSR is PSR-2, which is a coding style guide.
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.
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.
My suggestion is to just use require_once
99.9% of the time.
Using require
or include
instead implies that your code is not reusable elsewhere, i.e. that the scripts you're pulling in actually execute code instead of making available a class or some function libraries.
Variable scope is known as its boundary within which it can be visible or accessed from code. In other words, it is the context within which a variable is defined. There are only two scopes available in PHP namely local and global scopes.
- Local variables (local scope)
- Global variables (special global scope)
- Static variables (local scope)
- Function parameters (local scope) When a variable is accessed outside its scope it will cause PHP error undefined variable.
The
var_dump
function displays structured information about variables/expressions including its type and value. Arrays are explored recursively with values indented to show structure. It also shows which array values and object properties are references.The
print_r()
displays information about a variable in a way that's readable by humans. array values will be presented in a format that shows keys and elements. Similar notation is used for objects.
Consider:
$obj = (object) array('qualitypoint', 'technologies', 'India');
var_dump($obj)
will display below output in the screen:
object(stdClass)#1 (3) {
[0]=> string(12) "qualitypoint"
[1]=> string(12) "technologies"
[2]=> string(5) "India"
}
And, print_r($obj)
will display below output in the screen.
stdClass Object (
[0] => qualitypoint
[1] => technologies
[2] => India
)
- Single quoted strings will display things almost completely "as is."
- Double quote strings will display a host of escaped characters (including some regexes), and variables in the strings will be evaluated.
Things get evaluated in double quotes but not in single:
$s = "dollars";
echo 'This costs a lot of $s.'; // This costs a lot of $s.
echo "This costs a lot of $s."; // This costs a lot of dollars.
The set_time_limit(0)
added at the beginning of a script sets to infinite the time of execution to not have the PHP error 'maximum execution time exceeded.' It is also possible to specify this in the php.ini file.
Thanks π for reading and good luck on your next tech interview!
Explore 3800+ dev interview question here π Devinterview.io