PHP Interview Questions - Set 7

PHP Interview Questions

Share

This page contains PHP interview questions and answers.

Q1: How will you set header for JSON content in PHP?

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');

Q2: What is namespace in PHP?

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

Q3: How will you execute PHP script from command line?

If we have a PHP file awesome.php then we can execute using php command.

$ php awesome.php

Q4: How will you open the PHP interactive shell?

We can enter the PHP interactive shell by running the following command.

$ php -a

Q5: How will you prevent method overriding in PHP?

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...
  }
}

Q6: How will you set infinite PHP execution time?

We can put set_time_limit(0) at the start of the PHP script and it will set infinite PHP execution time.

Q7: Write PHP code to connect to MySQL database

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!');
}

Q8: How will you get the data passed by GET request in PHP?

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

Q9: Should you use mysql_connect to connect to MySQL database?

No, we should not use mysql_connect to connect to the MySQL database as it is deprecated.

Q10: How will you check if a variable holds a number value in PHP?

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

Recently Updated