\n```\n* Echo the data into the page somewhere, and use JavaScript to get the information from the DOM.\n```php\n
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.
To be able to pass a variable by reference, we use an ampersand in front of it, as follows:
$var1 = &$var2$GLOBALS mean?$GLOBALS is associative array including references to all variables which are currently defined in the global scope of the script.
== and ===?== casts between two different types if they are different=== 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 valueini_set()?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.
PHP supports only single inheritance; it means that a class can be extended from only one single class using the keyword 'extended'.
Consider:
function showMessage($hello = false){
echo ($hello) ? 'hello' : 'bye';
}print()echo and print are more or less the same. They are both used to output data to the screen.
The differences are:
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";
}notice is a non-critical error saying something went wrong in execution, something minor like an undefined variable.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.fatal error would terminate the code. Failure to satisfy a require() would generate this type of error, for example.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.
In PHP, objects passed by value.
die() and exit() functions in PHP?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.
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!
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.
stdClass in PHP?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; //42var_dump() and print_r()?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
)$a != $b and $a !== $b?!= means inequality (TRUE if $a is not equal to $b) and !== means non-identity (TRUE if $a is not identical to $b).
isset() and array_key_exists()? 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); // truerequire vs include?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.
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.
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.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.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 Referenceexec() vs system() vs passthru()?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.There are actually several approaches to do this:
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><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><script>
var data = <?php echo json_encode("42", JSON_HEX_TAG); ?>; // Don't forget the extra semicolon!
</script>/**
* 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.
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 $aThere are following functions which can be used from Exception class.
getMessage() − message of exceptiongetCode() − code of exceptiongetFile() − source filenamegetLine() − source linegetTrace() − n array of the backtrace()getTraceAsString() − formated string of traceException::__toString gives the string representation of the exception.array_map, array_walk and array_filter?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 truequery() vs execute()?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.
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"; Consider the code:
$a = new stdClass();
$a->foo = "bar";
$b = clone $a;
var_dump($a === $b);What will be echoed to the console?
Two instances of the same class with equivalent members do NOT match the === operator. So the answer is:
bool(false)Consider the code. What will be returned as a result?
$something = 0;
echo ('password123' == $something) ? 'true' : 'false';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' // truealso returns true.
require_once vs require?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.
extract()?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 = HorseRust 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...