Information Technology

PHP Interview Questions and Answers

PHP Interview Questions and Answers

PHP Interview Questions and Answers

1. What is PHP?
PHP stands for "Hypertext Preprocessor" which is a widely used, open-source, server-side scripting language. PHP is especially suited for creating dynamic websites, customized web applications and mobile APIs.

2. What is PEAR in PHP?
PEAR stands for "PHP Extension and Application Repository". PEAR is a framework and distribution system for reusable PHP components.

3. What is the difference between GET and POST methods?
- GET appends the data to the URL. POST uses HTTP POST method to pass data.

- In GET, data is visble to others, hence it is less secure. In POST, data is not visible to others, hence it is secure.

- In GET, limitation to send data (2048 Characters). In POST, no limitation to send data (depends on 'post_max_size' of PHP.INI).

- In GET, URL can be bookmarked. In POST, page can not be bookmarked.

- In GET, no support for multi-part binary input, while file uploading. POST supports multi-part binary input.

4. What is the difference between include() and require() functions?
Both include() and require() allows you to include file content, so that page content can be reused again.
The difference is that if an error occurs, require() throws a fatal error and stop the execution of the script, while include() generate a warning and continue with the execution of the code after.

5. What is the difference between unset() and unlink() functions?
unset() destroys the specified variables. unlink() deletes the specified file.

6. What is the difference between echo() and print() functions?
- echo() does not have return value. print() has return value of 1.

- echo() can take multiple parameters. print() allows one argument only.

- echo() is faster than print().

- echo() can not be used in expressions. print() can used in expressions.

7. What are Global/Super-global variables?
Global/Super-global variables are predefined variables in PHP, which are always accessible regardless of the scope.

Following are the Global/Super-global variables:
$GLOBALS,
$_REQUEST,
$_GET,
$_POST,
$_SESSION,
$_ENV,
$_SERVER,
$_FILES,
$_COOKIE

8. What is the difference between session and cookie functions?
Session helps us to store user data on the server, which we can use among multiple web pages.

Cookie is a tiny file placed on the user's machine by the server, for various purposes.

9. How can we delete cookie?
Cookie can be deleted by setting the expiration time to the past.

10. What is Abstract class?
An abstract class is a class that cannot be instantiated directly and may contain abstract methods that must be implemented by concrete subclasses. However, concrete subclasses of an abstract class can be instantiated.

11. What is an interface?
Interfaces allow you to specify what methods a class should implement. Interfaces make it easy to use a veriety of different classes in the same way. When one or more classes use the same interface, it is referred to as 'Polymorphism'.

12. What is Trait?
PHP only supports single inheritance, does not support to the multiple-inheritance. To overcome this, Trait came into focus. Trait is a concept which includes the collection of methods to use across mutliple classes.

13. What are the namespaces?
Namespaces are the qualifiers, for better organization by grouping classes that work together to perform a task. Also they allow the same name to be used for more than one class, with different class paths.

14. What are the magic methods?
Magic methods are the special methods that are called automatically when certain conditions are met. Every magic method follows certain rules:
- It should start with double underscore "__".
- They are predefined and neither can be created nor removed.
- They have reserved names and their names should not be used for other purposes.
- They are automatically called when certain criterias are met. 

15. Which are the magic methods?
__construct: called every time the object is created,
__destruct: called every time the object is destroyed,
__call($name, $parameter): executes when a method is called which is not defined yet,
__toString(): called when we need to convert the object into a string,
__get($name): called when non-existing variable is used,
__set($name, $value): called when non-existing variable is written,
__debugInfo(): called when an object is used inside var_dump() for debugging.

16. What is Static method?
Static method is method which can be called directly, without creating an instance of the class. We can access this method using class-name.

17. What is use of Final keyword?
Final keyword is used to prevent class inheritance or also to prevent method overriding.

18. Which are access modifiers?
- public: property or method can be accessed from everywhere. This is default.

- protected: property or method can be accessed within the class and by classes derived from that class.

- private: property or method can only be accessed within the class.

19. Is PHP a case-sensitive language?
PHP is a partial case-sensitive language. The variable names are completely case-sensitive but function names are not.

20. What is type hinting?
Type hinting is a concept that provides hints to function for the expected data type of arguments.

21. How is a constant defined in a PHP script?
The define() function lets us defining a constant as follows:
define ("TESTCONST", 124);

22. What are the different types of Array in PHP?
- Indexed Array – An array with a numeric index

- Associative Array – An array with strings as index

- Multidimensional Array – An array containing one or more arrays

23. What is Method Overriding?
Method Overriding involves creating a method in the child class that has the same name, parameters, and return type as a method in the parent class.

24. What is meant by 'passing the variable by reference'?
When we pass the variable by reference then it shares same memory location with passed variable. Means when we make change to passed variable then that change will be also affected to original variable.

25. What is the purpose of php.ini file?
PHP.ini is a configuration file containing your web server's PHP settings. It lets you control your site's PHP-related rules.

26. What is htaccess? What is use of this file?
The .htaccess file is an apache distributed server configuration file. You can use the .htaccess file to set server configurations for a specific directory.

27. Explain the difference between == and === in PHP.
'==' checks if the values of two operands are equal, but it does not check data types.
'===' checks if the values of two operands are equal and of the same data type.

28. How can you prevent SQL injection in PHP?
- Use prepared statements and parameterized queries with either PDO or mysqli.

- Input validation and sanitization to ensure data entered by users is safe.

- Avoid using user input directly in SQL queries without proper validation and escaping.

29. How can you handle errors and exceptions in PHP?
- Errors can be handled using the set_error_handler() function to define a custom error handler.

- Exceptions can be caught using try, catch, and finally blocks.

- Custom exceptions can be defined by extending the built-in Exception class.

30. How do you handle CORS (Cross-Origin Resource Sharing) in PHP?
- CORS headers can be set in PHP using the header() function to allow or deny cross-origin requests.

- For an example, to allow all cross-origin requests, you can set the 'Access-Control-Allow-Origin' header to '*'.

- Alternatively, you can specify specific origins to allow using the 'Access-Control-Allow-Origin' header.

31. What are Named Arguments?
PHP named arguments to pass arguments to a function based on the parameter names, rather than passing the parameter position-wise. In PHP 8, arguments are order-independent and self-documented. We can skip the optional parameters but specify only the required parameters.

Example:
<?php
 function sample($x = 2, $y = 4){
   echo "X: ", $x;
   echo " ";
   echo "Y: ", $y;
 }
 sample(y: 10, x: 20);
 //named arguments in different order

?>

32. What are Readonly Properties?
A readonly property can only be initialized once and only from the scope where it has been declared. Any other assignment or modification of the property will result in an Error exception.

Example:
<?php
 class Test {
   public readonly $teststr;
   public function __construct($str)
   {
     $this->teststr = $str;
   }
 }
?>