PHP: Interview Questions

 104
PHP: Interview Questions

1. Who is the Founder of PHP?

  • Rasmus Lerdorf is the founder of the PHP. He created PHP in 1994

2. What is PHP?

  • PHP stands for Hypertext Preprocessor.
  • It's an open-source, server-side scripting language.
  • PHP is widely used for creating dynamic and interactive web pages.
  • PHP code is executed on the server side.
  • It is compatible with many databases, including MySQL, PostgreSQL, SQLite, and more
  • It runs on various operating systems, including Windows, Linux, and macOS.

3. How to comment code in PHP?

In PHP, comments are used for your code not executed when the scripts run. You can add comments in three ways.

  • Single Line Comments:
<?php
// $name = 'John Doe';
# $name = 'John Doe';
?>
  • Multi-Line Comments:
<?php
/*
 * This is multiple line code comment block.
 */
?> 

 4. Case Sensitivity in PHP?

In PHP, the case insensitive:

  • Keywords: Keywords like if, else, while, echo, class methods & constructors, and function names are  case-insensitive.

In PHP, the case-sensitive:  Variables, Constants, array keys, and class properties.

 5. What was the old name of the PHP?
Personal Home Page.

 6. What is a Session?
A session in PHP is used to store the data(In variable) and that can be used across multiple pages of a website. This allows you to keep track of the user's information (e.g. Login credentials). It's super global variale.

Key Points about Sessions:

  • Server-Side Data Storage: Session data is stored on the server. Only session ID is stored on the user's computer (in Cookie) to uniquely identify the session on the server.
  • Temporary Data: The session variable last for the duration of the user's visit. The session ends when the user closes the browser or after a certain period of inactivity.
  • Security and Privacy: Sessions are more secure than cookies for storing the sensitive data.
     

 7. What is a Cookie in PHP?
A cookie in PHP is a small piece of data that is store in the user's browser (client-side). It is a super global variable. avoid using sensitive data in cookies. 
A cookie is created using the setcookie() function in PHP. Example: setcookie(name, value, expire, path, domain, secure, httponly) .
A cookie is deleted by using the expiration date. Example:  setcookie('user', ‘’,  time() - 3600).

8. What are super Globals variables in PHP?
Super global variables in PHP are predefined variables that are always accessible, These variables are built-in and provide an easy way to collect data from various sources, such as form submission, server information, and more. 

Some of the key superglobal variables in PHP are:

  • $GLOBALS : Contains all global variables in an array. It allows access to global variables from anywhere in the script .
  • $_SERVER : Information about headers, paths, and script location on the server.
  • $_REQUEST : Collect data from the GET & POST methods, as well as cookies.
  • $_GET : Holds form data that is submitted using the HTTP GET method.
  • $_POST : Holds form data that is submitted using the HTTP POST method.
  • $_FILES : Information about files uploaded to the server.
  • $_ENV : Environment variables that are passed to the script.
  • $_COOKIE : HTTP client data sent by the client to the server.
  • $_SESSION : Store session variables between multiple page requests.

9. What is the difference between $variable and $$variable?
In Php, the $variable is a simple variable, while the $$variable is a variable variable, meaning it references a variable's value as another variable name.

Php
$first_name = 'James';
$name = 'first_name';
echo $name;   // Output: first_name
echo $$name; // Output: James

10. What is the difference between $_GET and $_POST?
$_GET & $_POST are both used to collect form data sent via the HTTP request, but they differ in how they transmit and display data. 

 $_GET$_POST
Transmission Data is appended to the URL in name-value pairs. Data is sent in the body of the HTTP Request.
VisibilityAll the variables and their values are visible in the browser's address bar.Variables and values are not shown in the browser's address bar. data hidden from view during transmission.
Use CasesData retrieve is the main goal, such as search queries, filter, parameters, or pagination

Preferred for sending large amount of data, such as a file uploads or lengthy form submissions, because there is no size limitation.

Commonly used for transmitting sensitive information, such as password, private details.

LimitationURL Length restrictions: most browser limit the URL length to around 2048 characters.No Limit
SecurityLess secure because data is exposed in the URL. It should not be used for the sensitive information like password. More secure than GET as the Data is not exposed in the URL.
Post requests are recommended for handling sensitive and personal information. 
   

11. What are implode() and explode() functions in PHP ?
implode(): Converts an array into a string. you need to specify a delimiter to join the array elements into a single string.

$array = ['john', 'james', 'luke'];
$string = implode(', ', $array); //Outputs: joh, james, luke

explode(): Converting a string into an array by splitting it based on a specific delimiter.

$full_name = 'James Doe';
$array = explode(' ', $full_name); //Output: ['james', 'Doe'] 

12. What are the final classes and methods in PHP ?
Final Class: A Final class can not be extended. This means no other class can inherit from a final class.
Final Method: A Method declared as a final can not be overridden by any class that inherits from the class containing the final method. 

<?php
class BaseClass{
	final public function displayMessage(){
		echo '<br> Base Class: Test Keyword';
	}
}
class ChildClass extends BaseClass {
	public function showMessage(){
		echo '<br> Child class: new message';
	}
}
$baseObj = new BaseClass();
$childObj = new ChildClass();

$baseObj->displayMessage(); // Calling the final method from BaseClass
$childObj->displayMessage(); // Calling the final method from the BaseClass (inherit by ChildClass)
$childObj->showMessage(); // Calling the child class method

 13. What are the Different Types of Variables in PHP?

  • Integer: A non-decimal number (e.g., 1, 100, -50).
  • String: A sequence of characters enclosed in quotes (e.g., “Hello”, ‘PHP’).
  • Boolean: A true or false value (true or false)
  • NULL: Represent variable with no value.
  • Array: A collection of values, which can be indexed or associative.
  • Object: An instance of a class containing both data (properties) and functions (methods).
  • Resource: External resource, such as a file handle or database connection.

14. What is the difference between echo and print in PHP?

  •  echo :
    • It can output one or more strings.
    • It is faster than print because it does not return any value.
    • Syntax: echo “Hello”, “World”;
  •  print :
    • It can output one string at a time.
    • Always returns a value (1)
    • Slower than echo due to the return value.
    • Syntax: print “Hello world”;

 15. What are the Different Types of Arrays in PHP?

  • Indexed Arrays: It starts with a numeric index from zero (0). It stores strings, numbers, and even objects.
$fruits = array("Apple", "Banana","Watermelon");
echo $fruits[0]; // Outputs: Apple
  • Associative Arrays: Arrays with named keys.
$age = array('krunal' => 28, 'john' => 23, 'Harshank' => 27);
echo $age['krunal'] // Outputs: 28
  • Multidimensional Arrays: Arrays contain one or more arrays within them.
$contacts = array(
	array('Krunal', 'krunal@example.com'),
	array('John', 'john@example.com'),
);
echo $contacts[0][1] // Outputs: krunal@example.com

16. What is Encapsulation in PHP?

  • Encapsulation is the building of data (properties) & methods (functions) into a single unit know as a class.
  • It's a protection mechanism. restricting the direct access to certain components of class from the outside world. This helps prevent unauthorized access and modification of data.
  • In PHP, encapsulation is achieved using access modifiers ( public , protected , and private ), which determine the visibility and accessibility of the class members (properties & methods).   

17. What are access modifiers in PHP?

  • Access modifiers in PHP control the visibility and accessibility of the properties and methods within a class.
  • There are three types of access modifiers.
    • Public : properties and methods declared as public can be accessed from anywhere  – inside the class, outside the class and from the child class.
      - If no access modifier is specified, properties and methods are public.
    • Protected : It can be accessed within the class itself and by classes derived from that class. They can not be accessed outside the class.  
    • Private: It can be accessed within the class that defines them. They can not accessed from outside the class and child class.   

18. What is Inheritance in PHP?

  • Inheritance allows a child class to inherit properties and methods from a parent class. establishes a relationship between classes.
  • Inheritance is defined using the extends keywords in PHP. A child class inherits all the public and protected members of the parent class. It cannot inherit a private class.

19. What is abstract in PHP?

  • An abstract class is defined using the abstract keyword. We can not create an object for the abstract class. abstract method does not have any implementation (no body) code, it's just defined the argument. child class must be defined with the same name with redeclared abstract methods or a less restricted access modifier.

20. What is an interface in PHP?

  • An interface in PHP is defined using the interface keyword and is similar to an abstract class.
  • All methods declared in an interface must be public.
  • In an interface, we only declare methods without any implementation, whereas abstract classes can contain both properties and methods.
  • To use an interface, the implements keyword is used in a class definition.
interface Parts {
    public function displaySize($size);
    public function motherboard($type);
}
class Computer implements Parts {
    public function displaySize($size) {
        echo "Display size: " . $size . " inches";
    }
    public function motherboard($type) {
        echo "Motherboard: ". $type;
    }
}
$myComputer = new Computer();
$myComputer->displaySize(15); // Output: Display size: 15 inches

21. What are the traits?
Traits are a way to reusability of code across multiple classes, A trait is declared using a trait keyword, and it contains method & properties.

<?php
trait CalculationTrait {
    public function addSum($a, $b) {
        echo 'Sum: ' . ($a + $b);
    }
}
class Calculator {
    use CalculationTrait;
}
$obj = new Calculator();
$obj->addSum(5, 10);  // Output: Sum: 15

22. What is overriding in PHP?
Overriding in PHP, redefining a method in a child class that exists in its parent class. When a method in a parent class is overridden by a child class with the same method name and parameters. 
 

<?php
class BaseController
{
    public function show($id) {
        echo 'Base ID: ' . $id;
    }
}
class Profile extends BaseController {
    public function show($id) {
        echo 'User ID: ' . $id;
    }
}
// Creating an object of the parent class
$baseObject = new BaseController();
$baseObject->show(120); // Output: Base ID: 120

// Creating an object of the child class
$profileObject = new Profile();
$profileObject->show(160); // Output: User ID: 160

23. What are the HTTP response status codes and their names?

  • 401 : Unauthorized
  • 402 : Payment Required
  • 403 : Forbidden
  • 404 : Not Found
  • 405 : Method Not Allowed 
  • 500 : Internal Server Error
  • 501 : Not Implemented
  • 502 : Bad Gateway
  • 503 : Service unavailable
  • 504 : Gateway Timeout

 

 


Post a Comment

0Comments

* Please Don't Spam Here. All the Comments are Reviewed by Admin.

Post a Comment (0)