php-laravel
Interview questions for PHP, Laravel & MySQL by sabbir
Interview Questions for PHP:
**: What is method overriding in PHP ?
Method overriding in PHP is a fundamental concept of OOP, allowing a subclass to provide it's own implementation for a method that is inherited from the parent class(superclass). Here are the rules for method overriding:
- Have to have same method name.
- Have to have same number of parameters.
- Have to have same types of parameters.
Here is an example of how method overriding works in PHP:
class Animal {
public function speak() {
echo 'Animal speak';
}
}
class Dog extends Animal {
/**
* Here is the method overriding happens.
* You cannot have any params.
*/
public function speak() {
echo 'Dog Barks';
}
}
**: What is method overloading in PHP ?
Method overloading allows you define multiple methods with the same name in a class but with different parameter list. This means you can create different versions of a method that performs different actions depending on the parameters passed to the method. However, unlike other programming languages, PHP does not natively support method overloading by changing the number or types of arguments. Instead you can manually handle the parameters passed to method to handle the method overloading in PHP.
Here is an example:
class Math {
public static function sum(int $a): int {
if(func_num_args() == 1) {
return $a;
}
// or whatever you want to do with the parameters
return array_sum(func_get_args());
}
}
**: What is PEAR in PHP?
PEAR in PHP stands for "PHP Extension and Application Repository." It is a framework and distribution system for reusable PHP components, including libraries, packages, and extensions.
1: Is PHP a case sensitive language?
Yes, PHP is a case-sensitive language, meaning that it distinguishes between uppercase and lowercase letters in variable names, function names, and other identifiers.
2: What is the meaning of ‘escaping to PHP’?
"Escaping to PHP" refers to the process of embedding PHP code within an HTML document using PHP tags (<?php and ?>). This allows you to mix PHP code with HTML to create dynamic web pages.
3: What are the different types of PHP variables?
In PHP, variables can be categorized into different types based on their data types or what they store. The main types of PHP variables are:
-
Scalar Variables:
- Integer: Stores whole numbers, e.g.,
$num = 42. - Float (or Double): Stores floating-point numbers (numbers with decimal points), e.g.,
$pi = 3.14. - String: Stores text or characters, e.g.,
$name = "John". - Boolean: Stores either
trueorfalse, e.g.,$is_active = true.
- Integer: Stores whole numbers, e.g.,
-
Compound Variables:
- Array: Stores multiple values in an ordered list, e.g.,
$fruits = array("apple", "banana", "cherry"). - Object: Stores instances of user-defined classes, e.g.,
$car = new Car().
- Array: Stores multiple values in an ordered list, e.g.,
-
Special Variables:
- Resource: A special type used to hold references to external resources like database connections, file handles, etc.
- NULL: Represents a variable with no value or an undefined value, e.g.,
$empty_var = null.
-
Superglobals:
- Variables that are predefined in PHP and are accessible from any part of the script. These include
$_GET,$_POST,$_REQUEST,$_SESSION,$_COOKIE,$_SERVER,$_ENV, and more. They are used to handle HTTP requests, manage sessions, and access server-related information.
- Variables that are predefined in PHP and are accessible from any part of the script. These include
-
Variables with Special Prefixes:
- These variables have special meanings:
$GLOBALS: A superglobal that allows access to variables in the global scope.$_SESSION: A superglobal used for session variables.$_POSTand$_GET: Superglobals for handling form data sent via HTTP POST and GET methods.$_COOKIE: A superglobal for handling cookies.$_SERVER: A superglobal containing server-related information.
- These variables have special meanings:
These are the main types of PHP variables. Each type serves a specific purpose and is used in different situations within PHP scripts.
4: What are the rules for naming a PHP variable?
Rules for naming a PHP variable:
- Variable names must start with a letter or underscore.
- Variable names can only contain letters, numbers, and underscores.
- Variable names are case-sensitive.
- Variable names should not be PHP reserved words.
5: What are the rules to determine the “truth” of any value which is not already of the Boolean type?
In PHP, values are considered "truthy" if they are not:
- Empty strings
- Zero (0 or 0.0)
- NULL
- False (false boolean)
- An empty array
6: What is NULL?
NULL is a special value in PHP that represents the absence of a value or a variable that has not been assigned any value.
7: How do you define a constant in PHP?
To define a constant in PHP, you can use the define() function. For example:
define("MY_CONSTANT", 42);
8: What is the purpose of constant() function?
The constant() function in PHP is used to retrieve the value of a constant by providing its name as a string. For example, constant("MY_CONSTANT") would return the value of the constant named "MY_CONSTANT."
9: What are the differences between PHP constants and variables?
Differences between PHP constants and variables:
- Constants are defined using
define()and cannot be changed after definition, while variables can change their values. - Constants are typically used for values that should not be altered during the script's execution, like configuration settings.
- Variables are used for data that can change during the script's execution.
10: Name some of the constants in PHP and their purpose.
Some common PHP constants and their purposes:
PHP_VERSION: Holds the current PHP versionPHP_OS: Represents the name of the operating system.DIRECTORY_SEPARATOR: Contains the directory separator for the current OS.E_ERROR,E_WARNING, etc.: Error reporting constants for different error levels.
11: What is the difference between PHP4 and PHP5?
PHP5 introduced significant improvements and new features compared to PHP4, including:
- Enhanced object-oriented programming support.
- Introduction of visibility keywords (public, private, protected).
- Improved support for exceptions.
- Better performance and memory management
- Support for new data types, like the SimpleXML extension for parsing XML.
12: What is the meaning of a final class and a final method?
In PHP, a final class cannot be extended or subclassed, and a final method within a class cannot be overridden in any subclass. It's used to prevent further modification or extension of the class or method.
13: How can you compare objects in PHP?
To compare objects in PHP, you can use the == operator to check if they are equal in terms of properties and values, or the === operator to check if they are the same instance. The == operator compares values, while the === operator compares both values and data types.
14: How can PHP and Javascript interact?
PHP and JavaScript can interact through AJAX (Asynchronous JavaScript and XML) requests, which allow JavaScript to make requests to a PHP script on the server, retrieve data, and update the webpage without a full page refresh. They can also communicate through cookies, sessions, and embedding JavaScript code within PHP-generated HTML.
15: What are the data types in PHP?
Common data types in PHP include:
- Integer (int)
- Float (float)
- String (string)
- Boolean (bool)
- Array
- Object
- NULL
- Resource
- Callable
- Iterable (introduced in PHP 7.1)
16: What are constructor and destructor in PHP?
In PHP, a constructor is a special method called when an object of a class is created. It is used to initialize object properties. A destructor is a method that is called when an object is no longer referenced or when the script ends. It can be used to perform cleanup tasks.
17: What are include() and require() functions?
include() and require() are PHP functions used to include external files in a script. They include and evaluate the specified file. If the file is not found or has an error, require() will produce a fatal error, while include() will only produce a warning.
18: What is the main difference between require() and require_once()?
The main difference between require() and require_once() is that if the same file is included multiple times in a script, require_once() will ensure that it is included only once, preventing duplication.
19: What are different types of errors available in Php ?
Different types of errors in PHP:
- Parse errors (syntax errors)
- Fatal errors
- Warnings
- Notices
- Deprecated errors
- User-generated errors using
trigger_error()
20: What are the different types of Array in PHP?
Different types of arrays in PHP:
- Indexed arrays (numeric keys)
- Associative arrays (key-value pairs)
- Multidimensional arrays (arrays within arrays)
- Constant arrays (created with define())
- Typed arrays (introduced in PHP 8.0, with predefined data types for array elements)
21: What is the difference between “echo” and “print” in PHP?
In PHP, both echo and print are used to output text or data to the screen. However, there are some differences:
echois a language construct, whileprintis a function. This means thatechois slightly faster and more versatile in terms of what it can output.echocan output multiple values separated by commas, whileprintcan only output one value and always returns 1.echodoes not have a return value, whileprintreturns 1.echois often used for simple output, whileprintis less commonly used in modern PHP code.
22: Name some of the functions in PHP.
PHP has a wide range of built-in functions. Some commonly used functions include strlen, strpos, substr, date, array, explode, implode, file_get_contents, file_put_contents, mail, and many more.
23: What is the main difference between asp net and PHP?
ASP.NET is a web application framework developed by Microsoft, while PHP is a server-side scripting language. Some key differences include:
ASP.NETis typically used with theC#or Visual Basic.NET languages, whilePHPhas its own scripting language.ASP.NETis often used with Microsoft technologies like IIS and SQL Server, whilePHPis platform-agnostic and can run on various web servers and databases.ASP.NETis integrated with the Windows ecosystem, whereas PHP is more open-source and cross-platform.ASP.NETuses a compiled approach, while PHP is interpreted.
24: What is the use of session and cookies in PHP?
Sessions and cookies are used to maintain state information between HTTP requests in PHP:
- Sessions are server-side mechanisms for storing and retrieving data for a specific user across multiple pages during their visit to a website. They are typically more secure but require server resources.
- Cookies are small pieces of data stored on the client-side (user's browser). They can be used to store user-specific information and are sent with each HTTP request. They are less secure, as the user can view and modify them.
25: What is the difference between $message and $$message in PHP?
$messageis a variable that holds a single value.$$messageis a variable variable. It takes the value of $message and treats it as the name of another variable whose value it represents. For example, if$messagecontains the value"varName", then$$messageis equivalent to$varName.
26: How can we create a database using PHP and MySQL?
To create a database using PHP and MySQL, you typically need to perform the following steps:
- Connect to your MySQL server using PHP (e.g., mysqli_connect or PDO).
- Execute an SQL query to create a new database (e.g., CREATE DATABASE database_name).
- Check if the database creation was successful.
- Close the database connection.
Here's a simplified example using
mysqli:
$servername = "localhost";
$username = "username";
$password = "password";
// Create a connection
$conn = mysqli_connect($servername, $username, $password);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// Create a new database
$sql = "CREATE DATABASE mydb";
if (mysqli_query($conn, $sql)) {
echo "Database created successfully";
} else {
echo "Error creating database: " . mysqli_error($conn);
}
// Close the connection
mysqli_close($conn);
27: What is GET and POST method in PHP?
GET and POST are two HTTP request methods used to send data to a web server:
- GET: Data is appended to the URL as query parameters. It's primarily used for retrieving data. It has a limitation on the amount of data that can be sent (the data is visible in the URL).
- POST: Data is sent in the body of the HTTP request. It's used for sending larger amounts of data, like form submissions, and is more secure as the data is not visible in the URL.
28: What is the use of callback in PHP?
A callback in PHP is a reference to a function or method that can be passed as an argument to another function. Callbacks are often used for customizing the behavior of functions, especially in scenarios like sorting arrays or handling asynchronous operations.
For example, the usort function can take a callback function to customize the sorting behavior of an array.
29: What are PHP Magic Methods/Functions?
PHP magic methods are special methods with double underscores (e.g., __construct, __destruct, __get, __set, etc.) that provide predefined functionality in classes. They are automatically called by the PHP interpreter in response to specific events. Magic methods are commonly used for object initialization, property access, and more.
30: How can you encrypt password using PHP?
You should never store plain text passwords in a database. Instead, you should hash the passwords using a secure hashing algorithm like bcrypt. Here's a simplified example of how to hash and verify passwords in PHP:
// Hashing a password
$password = "user_password";
$hashed_password = password_hash($password, PASSWORD_BCRYPT);
// Verifying a password
$entered_password = "user_input_password";
if (password_verify($entered_password, $hashed_password)) {
// Password is correct
} else {
// Password is incorrect
}
31: How to connect to a URL in PHP?
To connect to a URL in PHP, you can use functions like file_get_contents() or cURL. Here's an example using file_get_contents():
$url = "https://example.com";
$data = file_get_contents($url);
For more advanced requests with options like setting headers and handling cookies, you can use the cURL library.
32: What is Type hinting in PHP?
Type hinting in PHP is a feature that allows you to specify the data type of a function's parameters or return value. This helps improve code clarity and can catch type-related errors early. For example:
function add(int $a, int $b): int {
return $a + $b;
}
33: What is the difference between runtime exception and compile time exception?
Runtime exceptions (also called runtime errors) occur during the execution of a program, while compile-time exceptions (also called compile-time errors) occur during the compilation of the code. Compile-time errors prevent the program from being compiled and executed, whereas runtime exceptions can occur after the program has started running.
34: Is PHP a loosely typed language?
Yes, PHP is a loosely typed language. In PHP, you don't need to explicitly declare data types for variables, and variables can change their data type during runtime. This flexibility can lead to unexpected behaviors if not handled carefully.
35: What is required to use the image function?
To use image functions in PHP, you need the GD (Graphics Draw) library extension enabled on your PHP server. You can enable it in your PHP configuration or compile PHP with GD support.
36: Mention the popular Content Management Systems (CMS) in PHP?
Some popular PHP-based Content Management Systems (CMS) include WordPress, Joomla, Drupal, and Magento.
37: Mention some of the constants in PHP and their purpose.
PHP has many predefined constants. Some common ones include:
__LINE__, __DIR__, __CLASS__ and more.
38: Explain the uses of explode() and implode() functions.
explode(): This function is used to split a string into an array based on a delimiter. For example, you can split a comma-separated string into an array of values.implode(), also known asjoin(): This function is used to join the elements of an array into a single string using a specified delimiter.
39: How to make a connection with MY SQL server?
To connect to a MySQL server in PHP, you can use functions like mysqli_connect, PDO, or the newer MySQLi (MySQL Improved) functions. Here's an example using MySQLi:
$servername = "localhost";
$username = "username";
$password = "password";
$database = "dbname";
$conn = mysqli_connect($servername, $username, $password, $database);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
40: Explain the difference between mysqli_connect and mysqli_pconnect.
mysqli_connect: This function establishes a regular (non-persistent) connection to the MySQL server. The connection is closed when the PHP script finishes execution.mysqli_pconnect: This function establishes a persistent connection to the MySQL server, which remains open even after the PHP script finishes execution. Persistent connections can reduce connection overhead but may have some limitations and drawbacks.
41: How do we access the data transfer through the URL with the POST method?
Data transferred through the POST method is accessed using the $_POST superglobal in PHP. For example:
$value = $_POST['input_name'];
Here, input_name is the name of the input field in an HTML form that was submitted with the POST method.
42: Explain the unlink() function in PHP.
The unlink() function in PHP is used to delete a file from the server. For example:
$file_path = "path/to/file.txt";
if (unlink($file_path)) {
echo "File deleted successfully.";
} else {
echo "Error deleting file.";
}
43: Explain what does the unset() function mean?
The unset() function in PHP is used to destroy a variable, making it no longer available for use in the script. It can also be used to remove elements from an array. For example:
$variable = "Hello";
unset($variable); // $variable is now undefined
$array = [1, 2, 3];
unset($array[1]); // Removes the element at index 1
44: What is the process to automatically run off incoming data?
It's not clear what you mean by "run off incoming data." If you are referring to processing incoming data automatically, you typically use server-side scripts to handle and process data received from web forms or other sources.