PHP Interview Questions
This page contains PHP interview questions and answers.
To set header we use the header
function. And to set header for JSON content we have to write the following.
header('Content-Type: application/json');
Namespaces are a way to encapsulate items like classes, interfaces, etc.
In the following example we are creating a class inside a file Awesome.php and it is inside the namespace MyProject.
namespace MyProject;
class Awesome {
// some code goes here...
}
In the following example we have another file SuperAwesome.php and it is using the Awesome.php class from the MyProject namespace.
use MyProject\Awesome;
// some code goes here...
If we have a PHP file awesome.php then we can execute using php
command.
$ php awesome.php
We can enter the PHP interactive shell by running the following command.
$ php -a
We can prevent method overriding by declaring the method of a class as a final
method.
In the following example we have a final method so, it can't be overridden by the child class.
class Awesome {
final public function hello() {
// some code goes here...
}
}
We can put set_time_limit(0)
at the start of the PHP script and it will set infinite PHP execution time.
In the following code we are using mysqli
class to connect to MySQL database.
// db credentials
define('DB_HOSTNAME', 'hostname');
define('DB_USERNAME', 'username');
define('DB_PASSWORD', 'password');
define('DB_DATABASE', 'database');
// connect
$mysqlicon = new mysqli(DB_HOSTNAME, DB_USERNAME, DB_PASSWORD, DB_DATABASE);
// check
if ($mysqlicon->connect_errno) {
die('Failed to connect to the database!');
}
Assuming we have a following URL link: https://example.com?name=yusufshakeel
and we want to get the name from the URL.
For this we will use the $_GET
array and we will look for name
.
Following code will print the name passed by GET request if the name parameter is set.
$name = $_GET['name'];
if (strlen($name)) {
echo "Name: $name";
} else {
echo "No name provided";
}
mysql_connect
to connect to MySQL database?No, we should not use mysql_connect
to connect to the MySQL database as it is deprecated.
For this we can use the is_numeric()
function.
In the following code we are checking if variable $x
holds a numeric value.
if (is_numeric($x)) {
echo "Yes x holds numeric value";
} else {
echo "No x holds something else";
}
ADVERTISEMENT