\n```\n* Echo the data into the page somewhere, and use JavaScript to get the information from the DOM.\n```php\n
\n \n
\n\n```\n* Echo the data directly to JavaScript.\n```php\n\n```"}},{"@type":"Question","name":"Is there a function to make a copy of a PHP array to another?","acceptedAnswer":{"@type":"Answer","text":"In PHP arrays are assigned by copy, while objects are assigned by reference so PHP will copy the array by default. References in PHP have to be explicit:\n\n```php\n$a = array(1,2);\n$b = $a; // $b will be a different array\n$c = &$a; // $c will be a reference to $a\n```"}},{"@type":"Question","name":"What is the difference between `==` and `===`?","acceptedAnswer":{"@type":"Answer","text":"* The operator `==` casts between two different types if they are different\n* The `===` operator performs a '_typesafe comparison_'\n\nThat means that it will only return true if both operands have the same type and the same value.\n\n```php\n1 === 1: true\n1 == 1: true\n1 === \"1\": false // 1 is an integer, \"1\" is a string\n1 == \"1\": true // \"1\" gets casted to an integer, which is 1\n\"foo\" === \"foo\": true // both operands are strings and have the same value\n```"}},{"@type":"Question","name":"What will be returned by this code?","acceptedAnswer":{"@type":"Answer","text":"Two instances of the same class with equivalent members do NOT match the `===` operator. So the answer is:\n\n```php\nbool(false)\n```"}},{"@type":"Question","name":"What's the difference between `isset()` and `array_key_exists()`? ","acceptedAnswer":{"@type":"Answer","text":"* `array_key_exists` will tell you if a key exists in an array and complains when `$a` does not exist.\n* `isset` will only return `true` if the key/variable exists **and is not `null`**. `isset` doesn't complain when `$a` does not exist.\n\nConsider:\n```js\n$a = array('key1' => 'Foo Bar', 'key2' => null);\n\nisset($a['key1']); // true\narray_key_exists('key1', $a); // true\n\nisset($a['key2']); // false\narray_key_exists('key2', $a); // true\n```"}},{"@type":"Question","name":"explain what is a closure in PHP and why does it use the “use” identifier?","acceptedAnswer":{"@type":"Answer","text":"This is how PHP expresses a **closure**. Basically what this means is that you are allowing the anonymous function to \"capture\" local variables (in this case, `$tax` and a reference to `$total`) _outside_ of it scope and preserve their values (or in the case of $total the reference to $total itself) as state within the anonymous function itself.\n\nA closure is a separate namespace, normally, you can not access variables defined outside of this namespace. \n\n* `use` allows you to access (use) the succeeding variables inside the closure. \n* `use` is early binding. That means the variable values are COPIED upon DEFINING the closure. So modifying $tax inside the closure has no external effect, unless it is a pointer, like an object is.\n* You can pass in variables as pointers like in case of `&$total`. This way, modifying the value of `$total` DOES HAVE an external effect, the original variable's value changes."}},{"@type":"Question","name":"What exactly are late static bindings in PHP?","acceptedAnswer":{"@type":"Answer","text":"Basically, it boils down to the fact that the `self` keyword does not follow the same rules of inheritance. `self` always resolves to the class in which it is used. This means that if you make a method in a parent class and call it from a child class, `self` will not reference the child as you might expect.\n\nLate static binding introduces a new use for the `static` keyword, which addresses this particular shortcoming. When you use `static`, it represents the class where you first use it, ie. it 'binds' to the runtime class.\n\nConsider:\n```php\nclass Car {\n public static\n function run() {\n return static::getName();\n }\n\n private static\n function getName() {\n return 'Car';\n }\n}\n\nclass Toyota extends Car {\n public static\n function getName() {\n return 'Toyota';\n }\n}\n\necho Car::run(); // Output: Car\necho Toyota::run(); // Output: Toyota\n```\n"}},{"@type":"Question","name":"What will be returned by this code? Explain the result.","acceptedAnswer":{"@type":"Answer","text":"The answer is `true`. You should never use `==` for string comparison. Even if you are comparing strings to strings, PHP will implicitly cast them to floats and do a numerical comparison if they appear numerical. `===` is OK. \n\nFor example \n\n```php\n'1e3' == '1000' // true\n```\n\nalso returns true."}},{"@type":"Question","name":"Provide some ways to mimic multiple constructors in PHP","acceptedAnswer":{"@type":"Answer","text":"I'd probably do something like this:\n\n```php\nclass Student\n{\n public function __construct() {\n // allocate your stuff\n }\n\n public static function withID( $id ) {\n $instance = new self();\n $instance->loadByID( $id );\n return $instance;\n }\n\n public static function withRow( array $row ) {\n $instance = new self();\n $instance->fill( $row );\n return $instance;\n }\n\n protected function loadByID( $id ) {\n // do query\n $row = my_awesome_db_access_stuff( $id );\n $this->fill( $row );\n }\n\n protected function fill( array $row ) {\n // fill all properties from array\n }\n}\n```\nThen if i want a Student where i know the ID:\n```php\n$student = Student::withID( $id );\n```\nTechnically you're not building multiple constructors, just static helper methods, but you get to avoid a lot of spaghetti code in the constructor this way.\n\nAnother way is to use **the mix of factory and fluent style**:\n```php\nclass Student\n{\n protected $firstName;\n protected $lastName;\n // etc.\n\n /**\n * Constructor\n */\n public function __construct() {\n // allocate your stuff\n }\n\n /**\n * Static constructor / factory\n */\n public static function create() {\n $instance = new self();\n return $instance;\n }\n\n /**\n * FirstName setter - fluent style\n */\n public function setFirstName( $firstName) {\n $this->firstName = $firstName;\n return $this;\n }\n\n /**\n * LastName setter - fluent style\n */\n public function setLastName( $lastName) {\n $this->lastName = $lastName;\n return $this;\n }\n}\n\n// create instance\n$student= Student::create()->setFirstName(\"John\")->setLastName(\"Doe\");\n```"}},{"@type":"Question","name":"What exactly is the the difference between `array_map`, `array_walk` and `array_filter`?","acceptedAnswer":{"@type":"Answer","text":"* `array_walk` takes an array and a function F and modifies it by replacing every element x with F(x).\n* `array_map` does the exact same thing **except** that instead of modifying in-place it will return a new array with the transformed elements.\n* `array_filter` with function F, instead of transforming the elements, will remove any elements for which F(x) **is not true**"}},{"@type":"Question","name":"Explain the difference between `exec()` vs `system()` vs `passthru()`?","acceptedAnswer":{"@type":"Answer","text":"* `exec()` is for calling a system command, and perhaps dealing with the output yourself.\n* `system()` is for executing a system command and immediately displaying the output - presumably text.\n* `passthru()` is for executing a system command which you wish the raw return from - presumably something binary."}},{"@type":"Question","name":"What is the difference between `var_dump()` and `print_r()`?","acceptedAnswer":{"@type":"Answer","text":"* 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.\n\n* 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.\n\nConsider:\n```php\n$obj = (object) array('qualitypoint', 'technologies', 'India');\n```\n`var_dump($obj) `will display below output in the screen:\n```\nobject(stdClass)#1 (3) {\n [0]=> string(12) \"qualitypoint\"\n [1]=> string(12) \"technologies\"\n [2]=> string(5) \"India\"\n}\n```\nAnd, `print_r($obj)` will display below output in the screen.\n```\nstdClass Object ( \n [0] => qualitypoint\n [1] => technologies\n [2] => India\n)\n```"}},{"@type":"Question","name":"How to measure execution times of PHP scripts?","acceptedAnswer":{"@type":"Answer","text":"You can use the `microtime` function for this. \n\nConsider:\n```php\n$start = microtime(true);\nwhile (...) {\n\n}\n$time_elapsed_secs = microtime(true) - $start;\n```"}},{"@type":"Question","name":"What is the best method to merge two PHP objects?","acceptedAnswer":{"@type":"Answer","text":"This works:\n```php\n$obj_merged = (object) array_merge((array) $obj1, (array) $obj2);\n```\nYou may also use `array_merge_recursive` to have a _deep copy_ behavior.\n\nOne more way to do that is:\n```php\nforeach($objectA as $k => $v) $objectB->$k = $v;\n``` \nThis is faster than the first answer in PHP versions < 7 (estimated 50% faster). But in PHP >= 7 the first answer is something like 400% faster. "}},{"@type":"Question","name":"How would you create a _Singleton_ class using PHP?","acceptedAnswer":{"@type":"Answer","text":"```php\n/**\n * Singleton class\n *\n */\nfinal class UserFactory {\n /**\n * Call this method to get singleton\n *\n * @return UserFactory\n */\n public static\n function Instance() {\n static $inst = null;\n if ($inst === null) {\n $inst = new UserFactory();\n }\n return $inst;\n }\n\n /**\n * Private ctor so nobody else can instantiate it\n *\n */\n private\n function __construct() {\n\n }\n}\n```\nTo use:\n\n```php\n$fact = UserFactory::Instance();\n$fact2 = UserFactory::Instance();\n```\n\nBut:\n\n```php\n$fact = new UserFactory()\n```\n\nThrows an error."}},{"@type":"Question","name":"Explain what the different PHP errors are","acceptedAnswer":{"@type":"Answer","text":"* A `notice` is a non-critical error saying something went wrong in execution, something minor like an undefined variable.\n* 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.\n* A `fatal error` would terminate the code. Failure to satisfy a require() would generate this type of error, for example."}},{"@type":"Question","name":"How can you enable error reporting in PHP?","acceptedAnswer":{"@type":"Answer","text":"Check if “`display_errors`” is equal “on” in the php.ini or declare “`ini_set('display_errors', 1)`” in your script.\n\nThen, include “`error_reporting(E_ALL)`” in your code to display all types of error messages during the script execution."}},{"@type":"Question","name":"Declare some function with default parameter","acceptedAnswer":{"@type":"Answer","text":"Consider:\n```php\nfunction showMessage($hello = false){\n echo ($hello) ? 'hello' : 'bye';\n}\n```"}},{"@type":"Question","name":"Compare MySQLi or PDO - what are the pros and cons?","acceptedAnswer":{"@type":"Answer","text":"Let's name some:\n\n* PDO is the standard, it's what most developers will expect to use. \n\n* Moving an application from one database to another isn't very common, but sooner or later you may find yourself working on another project using a different RDBMS. If you're at home with PDO then there will at least be one thing less to learn at that point.\n\n* A really nice thing with PDO is you can fetch the data, injecting it automatically in an object. \n\n* PDO has some features that help agains SQL injection\n\n* In sense of speed of execution MySQLi wins, but unless you have a good wrapper using MySQLi, its functions dealing with prepared statements are awful. inserts - almost equal, selects - mysqli is ~2.5% faster for non-prepared statements/~6.7% faster for prepared statements. "}},{"@type":"Question","name":"What is the difference between PDO's `query()` vs `execute()`?","acceptedAnswer":{"@type":"Answer","text":"* `query` runs a standard SQL statement and requires you to properly escape all data to avoid SQL Injections and other issues.\n* `execute` runs a prepared statement which allows you to bind parameters to avoid the need to escape or quote the parameters. execute will also perform better if you are repeating a query multiple times.\n\nBest practice is to stick with prepared statements and execute for increased _security_. Aside from the escaping on the client-side that it provides, a _prepared statement is compiled_ on the server-side once, and then can be passed different parameters at each execution."}},{"@type":"Question","name":" Is multiple inheritance supported in PHP?","acceptedAnswer":{"@type":"Answer","text":"PHP supports only single inheritance; it means that a class can be extended from only one single class using the keyword 'extended'."}},{"@type":"Question","name":"How can you pass a variable by reference?","acceptedAnswer":{"@type":"Answer","text":"To be able to pass a variable by **reference**, we use an _ampersand_ in front of it, as follows:\n```php\n$var1 = &$var2\n```"}},{"@type":"Question","name":"In PHP, objects are they passed _by value_ or _by reference_?","acceptedAnswer":{"@type":"Answer","text":"In PHP, objects passed by **value**."}},{"@type":"Question","name":"What does `$GLOBALS` mean?","acceptedAnswer":{"@type":"Answer","text":"`$GLOBALS` is associative array including references to all variables which are currently defined in the global scope of the script."}},{"@type":"Question","name":"What is the differences between `$a != $b` and `$a !== $b`?","acceptedAnswer":{"@type":"Answer","text":"`!=` means _inequality_ (TRUE if $a is not equal to $b) and `!==` means _non-identity_ (TRUE if $a is not identical to $b)."}},{"@type":"Question","name":"What is use of _Null Coalesce Operator_?","acceptedAnswer":{"@type":"Answer","text":"Null coalescing operator returns its first operand if it exists and is not NULL. Otherwise it returns its second operand.\n\nExample:\n\n```php\n$name = $firstName ?? $username ?? $placeholder ?? \"Guest\"; \n```"}},{"@type":"Question","name":"What is use of _Spaceship Operator_?","acceptedAnswer":{"@type":"Answer","text":"This `<=> ` operator will offer combined comparison in that it will:\n* Return 0 if values on either side _are equal_\n* Return 1 if value on _the left is greater_\n* Return -1 if the value on _the right is greater_\n\nConsider:\n```php\n//Comparing Integers\necho 1 <= > 1; //outputs 0\necho 3 <= > 4; //outputs -1\necho 4 <= > 3; //outputs 1\n\n//String Comparison\n\necho \"x\" <= > \"x\"; // 0\necho \"x\" <= > \"y\"; //-1\necho \"y\" <= > \"x\"; //1\n```"}},{"@type":"Question","name":"What is _PDO_ in PHP?","acceptedAnswer":{"@type":"Answer","text":"**PDO** stands for PHP Data Object.\n\nIt 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."}},{"@type":"Question","name":"Explain how we handle exceptions in PHP?","acceptedAnswer":{"@type":"Answer","text":"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\".\nAn exception can be thrown, and caught within PHP. \n\nTo handle exceptions, code may be surrounded in a `try` block.\nEach try must have at least one corresponding `catch` block. Multiple catch blocks can be used to catch different classes of exceptions.\nExceptions can be thrown (or re-thrown) within a catch block.\n\nConsider:\n\n```php\ntry {\n print \"this is our try block n\";\n throw new Exception();\n} catch (Exception $e) {\n print \"something went wrong, caught yah! n\";\n} finally {\n print \"this part is always executed n\";\n}\n```"}},{"@type":"Question","name":"Differentiate between _exception_ and _error_","acceptedAnswer":{"@type":"Answer","text":"- Recovering from `Error` is not possible. The only solution to errors is to terminate the execution. Where as you can recover from `Exception` by using either try-catch blocks or throwing exception back to caller.\n- You will not be able to handle the `Errors` using try-catch blocks. Even if you handle them using try-catch blocks, your application will not recover if they happen. On the other hand, `Exceptions` can be handled using try-catch blocks and can make program flow normal if they happen.\n- `Exceptions` are related to application where as `Errors` are related to environment in which application is running."}},{"@type":"Question","name":"What are the exception class functions?","acceptedAnswer":{"@type":"Answer","text":"There are following functions which can be used from `Exception` class.\n* `getMessage()` − message of exception\n* `getCode()` − code of exception\n* `getFile()` − source filename\n* `getLine()` − source line\n* `getTrace()` − n array of the `backtrace()`\n* `getTraceAsString()` − formated string of trace\n* `Exception::__toString` gives the string representation of the exception."}},{"@type":"Question","name":"How could we implement method overloading in PHP?","acceptedAnswer":{"@type":"Answer","text":"You cannot overload PHP functions. Function signatures are based only on their names and do not include argument lists, so you cannot have two functions with the same name. \n\nYou can, however, declare a **variadic function** that takes in a variable number of arguments. You would use `func_num_args()` and `func_get_arg()` to get the arguments passed, and use them normally.\n\nConsider:\n```php\nfunction myFunc() {\n for ($i = 0; $i < func_num_args(); $i++) {\n printf(\"Argument %d: %s\\n\", $i, func_get_arg($i));\n }\n}\n\n/*\nArgument 0: a\nArgument 1: 2\nArgument 2: 3.5\n*/\nmyFunc('a', 2, 3.5);\n```"}},{"@type":"Question","name":"Differentiate between parameterised and non parameterised functions","acceptedAnswer":{"@type":"Answer","text":"- **Non parameterised functions** don't take any parameter at the time of calling.\n- **Parameterised functions** take one or more arguments while calling. These are used at run time of the program when output depends on dynamic values given at run time\nThere are two ways to access the parameterised function:\n 1. _call by value_: (here we pass the value directly )\n 2. _call by reference_: (here we pass the address location where the value is stored)"}},{"@type":"Question","name":"Explain function call _by reference_","acceptedAnswer":{"@type":"Answer","text":"In case of call by reference, actual value is modified if it is modified inside the function. In such case, we need to use `&` symbol with formal arguments. The `&` represents reference of the variable.\n\nExample:\n\n```php \nfunction adder(&$str2) { \n $str2 .= 'Call By Reference'; \n}\n$str = 'This is '; \nadder($str); \necho $str; \n```\n\nOutput:\n```sh\nThis is Call By Reference\n```"}},{"@type":"Question","name":"What is the use of `ini_set()`?","acceptedAnswer":{"@type":"Answer","text":"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.\n\nGiven line of code will enable the display_error setting for the script if it’s disabled.\n\n`ini_set('display_errors', '1');`\n\nWe 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."}},{"@type":"Question","name":"Why do we use `extract()`?","acceptedAnswer":{"@type":"Answer","text":"The `extract()` function imports variables into the local symbol table from an array.\nThis function uses array keys as variable names and values as variable values. For each element it will create a variable in the current symbol table.\nThis function returns the number of variables extracted on success.\n\nExample:\n\n```php\n$a = \"Original\";\n$my_array = array(\"a\" => \"Cat\",\"b\" => \"Dog\", \"c\" => \"Horse\");\nextract($my_array);\necho \"\\$a = $a; \\$b = $b; \\$c = $c\";\n```\n\nOutput:\n\n```sh\n$a = Cat; $b = Dog; $c = Horse\n```"}},{"@type":"Question","name":"Differentiate between echo and `print()`","acceptedAnswer":{"@type":"Answer","text":"`echo` and `print` are more or less the same. They are both used to output data to the screen.\n\nThe differences are: \n- echo has no return value while print has a return value of 1 so it can be used in expressions. \n- echo can take multiple parameters (although such usage is rare) while print can take one argument. \n- echo is faster than print."}},{"@type":"Question","name":"Does PHP have threading?","acceptedAnswer":{"@type":"Answer","text":"Standard php does not provide any multithreading but there is an (experimental) extension that actually does - `pthreads`. The next best thing would be to simply have one script execute another via CLI, but that's a bit rudimentary. Depending on what you are trying to do and how complex it is, this may or may not be an option."}},{"@type":"Question","name":"Is PHP single or multi threaded?","acceptedAnswer":{"@type":"Answer","text":"PHP is not single threaded by nature. It is, however, the case that the most common installation of PHP on unix systems is a single threaded setup, as is the most common Apache installation, and nginx doesn't have a thread based architecture whatever. In the most common Windows setup and some more advanced unix setups, PHP can and does operate multiple interpreter threads in one process.\n\nPHP as an interpreter had support for multi-threading since the year 2000."}}]}
FullStackFSCCafé
 
 
Sign in with GoogleSign in with Google. Opens in new tab
Kill Your Tech Interview
3877 Full-Stack, Algorithms & System Design Interview Questions
Answered To Get Your Next Six-Figure Job Offer
      
🤖 Having Machine Learning & DS Interview? Check  MLStack.Cafe - 1704 Data Science & ML Interview Questions & Answers!Having ML & DS Interview? Check 🤖 MLStack.Cafe - 1704 ML & DS Interview Questions and Answers

45 Advanced PHP Interview Questions That May Land You a Job

The average PHP Developer salary in Australia is $95,000 per year or $48.72 per hour. Entry level positions start at $55,000 per year while most experienced workers make up to $161,500 per year. Follow along and learn 45 advanced PHP interview questions that may land you a job.

Q1: 
How can you pass a variable by reference?

Answer

To be able to pass a variable by reference, we use an ampersand in front of it, as follows:

$var1 = &$var2

Having Tech or Coding Interview? Check 👉 82 PHP Interview Questions
Source: guru99.com

Q2: 
What does $GLOBALS mean?

Answer

$GLOBALS is associative array including references to all variables which are currently defined in the global scope of the script.


Having Tech or Coding Interview? Check 👉 82 PHP Interview Questions
Source: guru99.com

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

Answer
  • 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

Having Tech or Coding Interview? Check 👉 82 PHP Interview Questions

Q4: 
What is the use of ini_set()?

Answer

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.


Having Tech or Coding Interview? Check 👉 82 PHP Interview Questions

Q5: 
Is multiple inheritance supported in PHP?

Answer

PHP supports only single inheritance; it means that a class can be extended from only one single class using the keyword 'extended'.


Having Tech or Coding Interview? Check 👉 82 PHP Interview Questions
Source: guru99.com

Q6: 
Declare some function with default parameter

Answer

Consider:

function showMessage($hello = false){
  echo ($hello) ? 'hello' : 'bye';
}

Having Tech or Coding Interview? Check 👉 82 PHP Interview Questions
Source: codementor.io

Q7: 
Differentiate between echo and print()

Answer

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.

Having Tech or Coding Interview? Check 👉 82 PHP Interview Questions

Q8: 
Explain how we handle exceptions in PHP?

Answer

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";
}

Having Tech or Coding Interview? Check 👉 82 PHP Interview Questions
🤖 Having Machine Learning & DS Interview? Check  MLStack.Cafe - 1704 Data Science & ML Interview Questions & Answers!Having ML & DS Interview? Check 🤖 MLStack.Cafe - 1704 ML & DS Interview Questions and Answers

Q9: 
Explain what the different PHP errors are

Answer
  • 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.

Having Tech or Coding Interview? Check 👉 82 PHP Interview Questions
Source: pangara.com

Q10: 
How can you enable error reporting in PHP?

Answer

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.


Having Tech or Coding Interview? Check 👉 82 PHP Interview Questions
Source: codementor.io

Q11: 
In PHP, objects are they passed by value or by reference?

Answer

In PHP, objects passed by value.


Having Tech or Coding Interview? Check 👉 82 PHP Interview Questions
Source: guru99.com

Q12: 
What are the differences between die() and exit() functions in PHP?

Answer

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.


Having Tech or Coding Interview? Check 👉 82 PHP Interview Questions

Q13: 
What are the main differences between const vs define

Answer

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!


Having Tech or Coding Interview? Check 👉 82 PHP Interview Questions

Q14: 
What is PDO in PHP?

Answer

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.


Having Tech or Coding Interview? Check 👉 82 PHP Interview Questions

Q15: 
What is stdClass in PHP?

Answer

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

Having Tech or Coding Interview? Check 👉 82 PHP Interview Questions
🤖 Having Machine Learning & DS Interview? Check  MLStack.Cafe - 1704 Data Science & ML Interview Questions & Answers!Having ML & DS Interview? Check 🤖 MLStack.Cafe - 1704 ML & DS Interview Questions and Answers

Q16: 
What is the difference between var_dump() and print_r()?

Answer
  • 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
)

Having Tech or Coding Interview? Check 👉 82 PHP Interview Questions

Q17: 
What is the differences between $a != $b and $a !== $b?

Answer

!= means inequality (TRUE if $a is not equal to $b) and !== means non-identity (TRUE if $a is not identical to $b).


Having Tech or Coding Interview? Check 👉 82 PHP Interview Questions
Source: guru99.com

Q18: 
What's the difference between isset() and array_key_exists()?

Answer
  • array_key_exists will tell you if a key exists in an array and complains when $a does not exist.
  • isset will only return true if the key/variable exists and is not null. 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

Having Tech or Coding Interview? Check 👉 82 PHP Interview Questions

Q19: 
When should I use require vs include?

Answer

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.


Having Tech or Coding Interview? Check 👉 82 PHP Interview Questions

Q20: 
Check if PHP array is associative

Answer

Consider:

function has_string_keys(array $array) {
  return count(array_filter(array_keys($array), 'is_string')) > 0;
}

If there is at least one string key, $array will be regarded as an associative array.


Having Tech or Coding Interview? Check 👉 82 PHP Interview Questions

Q21: 
Differentiate between exception and error

Answer
  • Recovering from Error is not possible. The only solution to errors is to terminate the execution. Where as you can recover from Exception by using either try-catch blocks or throwing exception back to caller.
  • You will not be able to handle the Errors using try-catch blocks. Even if you handle them using try-catch blocks, your application will not recover if they happen. On the other hand, Exceptions can be handled using try-catch blocks and can make program flow normal if they happen.
  • Exceptions are related to application where as Errors are related to environment in which application is running.

Having Tech or Coding Interview? Check 👉 82 PHP Interview Questions

Q22: 
Differentiate between parameterised and non parameterised functions

Answer
  • Non parameterised functions don't take any parameter at the time of calling.
  • Parameterised functions take one or more arguments while calling. These are used at run time of the program when output depends on dynamic values given at run time There are two ways to access the parameterised function:
  1. call by value: (here we pass the value directly )
  2. call by reference: (here we pass the address location where the value is stored)

Having Tech or Coding Interview? Check 👉 82 PHP Interview Questions
🤖 Having Machine Learning & DS Interview? Check  MLStack.Cafe - 1704 Data Science & ML Interview Questions & Answers!Having ML & DS Interview? Check 🤖 MLStack.Cafe - 1704 ML & DS Interview Questions and Answers

Q23: 
Explain function call by reference

Answer

In case of call by reference, actual value is modified if it is modified inside the function. In such case, we need to use & symbol with formal arguments. The & represents reference of the variable.

Example:

function adder(&$str2) {  
    $str2 .= 'Call By Reference';  
}
$str = 'This is ';  
adder($str);  
echo $str;  

Output:

This is Call By Reference

Having Tech or Coding Interview? Check 👉 82 PHP Interview Questions

Q24: 
Explain the difference between exec() vs system() vs passthru()?

Answer
  • exec() is for calling a system command, and perhaps dealing with the output yourself.
  • system() is for executing a system command and immediately displaying the output - presumably text.
  • passthru() is for executing a system command which you wish the raw return from - presumably something binary.

Having Tech or Coding Interview? Check 👉 82 PHP Interview Questions

Q25: 
How do I pass variables and data from PHP to JavaScript?

Answer

There are actually several approaches to do this:

  • Use AJAX to get the data you need from the server.
    Consider get-data.php:
echo json_encode(42);

Consider index.html:

<script>
    function reqListener () {
      console.log(this.responseText);
    }

    var oReq = new XMLHttpRequest(); // New request object
    oReq.onload = function() {
        // This is where you handle what to do with the response.
        // The actual data is found on this.responseText
        alert(this.responseText); // Will alert: 42
    };
    oReq.open("get", "get-data.php", true);
    //                               ^ Don't block the rest of the execution.
    //                                 Don't wait until the request finishes to
    //                                 continue.
    oReq.send();
</script>
  • Echo the data into the page somewhere, and use JavaScript to get the information from the DOM.
<div id="dom-target" style="display: none;">
    <?php
        $output = "42"; // Again, do some operation, get the output.
        echo htmlspecialchars($output); /* You have to escape because the result
                                           will not be valid HTML otherwise. */
    ?>
</div>
<script>
    var div = document.getElementById("dom-target");
    var myData = div.textContent;
</script>
  • Echo the data directly to JavaScript.
<script>
    var data = <?php echo json_encode("42", JSON_HEX_TAG); ?>; // Don't forget the extra semicolon!
</script>

Having Tech or Coding Interview? Check 👉 82 PHP Interview Questions

Q26: 
How would you create a Singleton class using PHP?

Answer
/**
 * Singleton class
 *
 */
final class UserFactory {
    /**
     * Call this method to get singleton
     *
     * @return UserFactory
     */
    public static
    function Instance() {
        static $inst = null;
        if ($inst === null) {
            $inst = new UserFactory();
        }
        return $inst;
    }

    /**
     * Private ctor so nobody else can instantiate it
     *
     */
    private
    function __construct() {

    }
}

To use:

$fact = UserFactory::Instance();
$fact2 = UserFactory::Instance();

But:

$fact = new UserFactory()

Throws an error.


Having Tech or Coding Interview? Check 👉 82 PHP Interview Questions

Q27: 
Is there a function to make a copy of a PHP array to another?

Answer

In PHP arrays are assigned by copy, while objects are assigned by reference so PHP will copy the array by default. References in PHP have to be explicit:

$a = array(1,2);
$b = $a; // $b will be a different array
$c = &$a; // $c will be a reference to $a

Having Tech or Coding Interview? Check 👉 82 PHP Interview Questions

Q28: 
What are the exception class functions?

Answer

There are following functions which can be used from Exception class.

  • getMessage() − message of exception
  • getCode() − code of exception
  • getFile() − source filename
  • getLine() − source line
  • getTrace() − n array of the backtrace()
  • getTraceAsString() − formated string of trace
  • Exception::__toString gives the string representation of the exception.

Having Tech or Coding Interview? Check 👉 82 PHP Interview Questions

Q29: 
What exactly is the the difference between array_map, array_walk and array_filter?

Answer
  • array_walk takes an array and a function F and modifies it by replacing every element x with F(x).
  • array_map does the exact same thing except that instead of modifying in-place it will return a new array with the transformed elements.
  • array_filter with function F, instead of transforming the elements, will remove any elements for which F(x) is not true

Having Tech or Coding Interview? Check 👉 82 PHP Interview Questions
🤖 Having Machine Learning & DS Interview? Check  MLStack.Cafe - 1704 Data Science & ML Interview Questions & Answers!Having ML & DS Interview? Check 🤖 MLStack.Cafe - 1704 ML & DS Interview Questions and Answers

Q30: 
What is the difference between PDO's query() vs execute()?

Answer
  • query runs a standard SQL statement and requires you to properly escape all data to avoid SQL Injections and other issues.
  • execute runs a prepared statement which allows you to bind parameters to avoid the need to escape or quote the parameters. execute will also perform better if you are repeating a query multiple times.

Best practice is to stick with prepared statements and execute for increased security. Aside from the escaping on the client-side that it provides, a prepared statement is compiled on the server-side once, and then can be passed different parameters at each execution.


Having Tech or Coding Interview? Check 👉 82 PHP Interview Questions

Q31: 
What is use of Null Coalesce Operator?

Answer

Null coalescing operator returns its first operand if it exists and is not NULL. Otherwise it returns its second operand.

Example:

$name = $firstName ?? $username ?? $placeholder ?? "Guest"; 

Having Tech or Coding Interview? Check 👉 82 PHP Interview Questions

Q32: 
What will be returned by this code?

Problem

Consider the code:

$a = new stdClass();
$a->foo = "bar";
$b = clone $a;
var_dump($a === $b);

What will be echoed to the console?

Answer

Two instances of the same class with equivalent members do NOT match the === operator. So the answer is:

bool(false)

Having Tech or Coding Interview? Check 👉 82 PHP Interview Questions

Q33: 
What will be returned by this code? Explain the result.

Problem

Consider the code. What will be returned as a result?

$something = 0;
echo ('password123' == $something) ? 'true' : 'false';
Answer

The answer is true. You should never use == for string comparison. Even if you are comparing strings to strings, PHP will implicitly cast them to floats and do a numerical comparison if they appear numerical. === is OK.

For example

'1e3' == '1000' // true

also returns true.


Having Tech or Coding Interview? Check 👉 82 PHP Interview Questions

Q34: 
When should I use require_once vs require?

Answer

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.

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.


Having Tech or Coding Interview? Check 👉 82 PHP Interview Questions

Q35: 
Why do we use extract()?

Answer

The extract() function imports variables into the local symbol table from an array. This function uses array keys as variable names and values as variable values. For each element it will create a variable in the current symbol table. This function returns the number of variables extracted on success.

Example:

$a = "Original";
$my_array = array("a" => "Cat","b" => "Dog", "c" => "Horse");
extract($my_array);
echo "\$a = $a; \$b = $b; \$c = $c";

Output:

$a = Cat; $b = Dog; $c = Horse

Having Tech or Coding Interview? Check 👉 82 PHP Interview Questions

Q36: 
Compare MySQLi or PDO - what are the pros and cons?

Answer
Join FullStack.Cafe to open this Answer. It's Free!
Sign in with GoogleSign in with Google. Opens in new tab
Join 120k+ Developer Who Trust FullStack.Cafe
🤖 Having Machine Learning & DS Interview? Check  MLStack.Cafe - 1704 Data Science & ML Interview Questions & Answers!Having ML & DS Interview? Check 🤖 MLStack.Cafe - 1704 ML & DS Interview Questions and Answers

Q37: 
Does PHP have threading?

Answer
Join FullStack.Cafe to open this Answer. It's Free!
Sign in with GoogleSign in with Google. Opens in new tab
Join 120k+ Developer Who Trust FullStack.Cafe

Q38: 
How to measure execution times of PHP scripts?

Answer
Join FullStack.Cafe to open this Answer. It's Free!
Sign in with GoogleSign in with Google. Opens in new tab
Join 120k+ Developer Who Trust FullStack.Cafe

Q39: 
Is PHP single or multi threaded?

Answer
Join FullStack.Cafe to open this Answer. It's Free!
Sign in with GoogleSign in with Google. Opens in new tab
Join 120k+ Developer Who Trust FullStack.Cafe

Q40: 
What exactly are late static bindings in PHP?

Answer
Join FullStack.Cafe to open this Answer. It's Free!
Sign in with GoogleSign in with Google. Opens in new tab
Join 120k+ Developer Who Trust FullStack.Cafe

Q41: 
What is the best method to merge two PHP objects?

Answer
Join FullStack.Cafe to open this Answer. It's Free!
Sign in with GoogleSign in with Google. Opens in new tab
Join 120k+ Developer Who Trust FullStack.Cafe

Q42: 
What is use of Spaceship Operator?

Answer
Join FullStack.Cafe to open this Answer. It's Free!
Sign in with GoogleSign in with Google. Opens in new tab
Join 120k+ Developer Who Trust FullStack.Cafe

Q43: 
explain what is a closure in PHP and why does it use the “use” identifier?

Answer
Join FullStack.Cafe to open this Answer. It's Free!
Sign in with GoogleSign in with Google. Opens in new tab
Join 120k+ Developer Who Trust FullStack.Cafe
🤖 Having Machine Learning & DS Interview? Check  MLStack.Cafe - 1704 Data Science & ML Interview Questions & Answers!Having ML & DS Interview? Check 🤖 MLStack.Cafe - 1704 ML & DS Interview Questions and Answers

Q44: 
How could we implement method overloading in PHP?

Answer
Unlock FullStack.Cafe to open all answers and get your next figure job offer!
Share this blog post to open Expert question!

Q45: 
Provide some ways to mimic multiple constructors in PHP

Answer
Unlock FullStack.Cafe to open all answers and get your next figure job offer!
Share this blog post to open Expert question!
 

Rust has been Stack Overflow’s most loved language for four years in a row and emerged as a compelling language choice for both backend and system developers, offering a unique combination of memory safety, performance, concurrency without Data races...

Clean Architecture provides a clear and modular structure for building software systems, separating business rules from implementation details. It promotes maintainability by allowing for easier updates and changes to specific components without affe...

Azure Service Bus is a crucial component for Azure cloud developers as it provides reliable and scalable messaging capabilities. It enables decoupled communication between different components of a distributed system, promoting flexibility and resili...

Cosmos DB has gained popularity among developers and organizations across various industries, including finance, e-commerce, gaming, IoT, and more. Follow along and learn the 24 most common and advanced Azure Cosmos DB interview questions and answers...
More than any other NoSQL database, and dramatically more than any relational database, MongoDB's document-oriented data model makes it exceptionally easy to add or change fields, among other things. It unlocks Iteration on the project. Iteration f...
Unit Tests and Test Driven Development (TDD) help you really understand the design of the code you are working on. Instead of writing code to do something, you are starting by outlining all the conditions you are subjecting the code to and what outpu...
Domain-Driven Design is nothing magical but it is crucial to understand the importance of Ubiquitous Language, Domain Modeling, Context Mapping, extracting the Bounded Contexts correctly, designing efficient Aggregates and etc. before your next DDD p...
At its core, Microsoft Azure is a public cloud computing platform - with solutions including Infrastructure as a Service (IaaS), Platform as a Service (PaaS), and Software as a Service (SaaS) that can be used for services such as analytics, virtual c...
As an asynchronous event-driven JavaScript runtime, Node.js is designed to build scalable network applications. Follow along to refresh your knowledge and explore the 52 most frequently asked and advanced Node JS Interview Questions and Answers every...
Dependency Injection is most useful when you're aiming for code reuse, versatility and robustness to changes in your problem domain. DI is also useful for decoupling your system. DI also allows easier unit testing without having to hit a database and...