Interview Questions on PHP
21. How to create an array in php?
Ex :- $array_name = array("value1", " value2", " value3");
22. Explain foreach statement in php?
Syntax :-
foreach (array_expression as $value)
statement
Ex :-
$arr = array(1, 2, 3, 4);
foreach ($arr as &$value) {
$value = $value * 2;
}
23. How to write “ in string which is enclosed with in double quotes?
Use \
Ex :- “this is \“Text\” enclosed in double queotes”.
24. What is pass by value and pass by reference?
Pass By value :-
Pass variables as arguments to the function.
Syntax :-
<?php
function foo($var)
{
$var++;
}
$a=5;
foo($a);
// $a is 6 here
?>
Passing by Reference :-
You can pass a variable by reference to a function so the function can modify the variable.
Syntax:
<?php
function foo(&$var)
{
$var++;
}
$a=5;
foo($a);
// $a is 6 here
?>
25. How to write Exception handlings in php?
Syntax :-
try {
// Code goes here
}
catch(Exception $e) {
echo 'Message: ' .$e->getMessage();
}
Ex: -
try {
checkNum(2);
//If the exception is thrown, this text will not be shown
echo 'If you see this, the number is 1 or below';
}
//catch exception
catch(Exception $e) {
echo 'Message: ' .$e->getMessage();
}
26. If we write return in both try and finally block which block will it execute?
finally
27. How to declare constant values in php?
1. If we want to declare out side of class use
define(const_name', 'value');
2. If we want to write inside class then use
const const_name = value;
28. How to declare global variable in php?
Declare those varibles outside function.
Ex :-
<?php
$a = 1; /* global scope */
function test()
{
echo $a; /* reference to local scope variable */
}
test();
?>
29. How to write and execute constructor in php?
Syntax :-
void __construct ([ mixed $args = "" [, $... ]] )
Ex :-
<?php
class BaseClass {
function __construct() {
print "In BaseClass constructor\n";
}
}
?>
Constructors will be executed at the time of creation of objects.
30. Explian function overloading?
Function Over Loading :- Function Overloading happens if multiple functions exist with same name but different parameters.
Ex :-
class Foo {
function myFoo() {
return "Foo";
}
function myFoo($a) {
return "Foo with one arg";
}
}
$foo = new Foo;
echo($foo->myFoo()); //"Foo"
echo($foo->myFoo("a")); //