PHP Question and Answer
PHP stands for "Hypertext Preprocessor". It is a widely-used open-source server-side scripting language designed for web development. PHP scripts are executed on the server and the result is returned to the browser as plain HTML.
Both `echo` and `print` are used to output data to the screen in PHP. The difference is that `echo` can output multiple strings separated by commas and is slightly faster, whereas `print` returns a value (1) and can only output one string at a time.
In PHP, a variable is declared using the dollar sign ($) followed by the variable name. For example: $name = "John";
PHP supports several data types: String, Integer, Float (double), Boolean, Array, Object, NULL, and Resource.
Arrays in PHP can be created using the array()
function or short syntax []
. Example: $fruits = array("apple", "banana", "cherry");
or $fruits = ["apple", "banana", "cherry"];
A PHP block starts with and ends with
?>
. All PHP code should be written inside these tags.
==
checks for value equality, while ===
checks for both value and data type equality.
Single-line comments use //
or #
, and multi-line comments use /* ... */
.
Constants are name-value pairs that cannot be changed during execution. They are defined using the define()
function.
You use the function
keyword. Example: function greet() { echo "Hello"; }
Superglobals are built-in arrays accessible from anywhere in the script, like $_GET
, $_POST
, $_SESSION
, $_COOKIE
, and $_SERVER
.
Form data is handled using $_GET
for GET requests and $_POST
for POST requests.
Both include and require are used to include PHP files. The difference is that require
causes a fatal error if the file is missing, while include
only gives a warning.
A session allows you to store user information across multiple pages. Use session_start()
to begin a session and $_SESSION
to store data.
A cookie is a small file that the server embeds on the user's computer. In PHP, you can set a cookie using setcookie()
and retrieve it using $_COOKIE
.
isset()
checks whether a variable is set and is not null. It returns true if the variable exists and is not null.
unset()
is used to destroy a variable, whereas unlink()
is used to delete a file from the file system.
The header()
function is used to send raw HTTP headers to the browser. It is commonly used for redirects and content type declarations.
GET
appends data to the URL and has size limits, while POST
sends data in the HTTP body and has no size limits. POST is more secure for sensitive data.
You can connect using mysqli_connect("hostname", "username", "password", "database")
or with PDO for more flexibility and security.
PDO (PHP Data Objects) is a database access layer that provides a uniform method for accessing multiple databases securely using prepared statements.
Prepared statements are used to execute the same query repeatedly with different values. They protect against SQL injection by separating the query logic from the data.
Errors in PHP can be handled using try...catch
blocks for exceptions or by setting custom error handlers using set_error_handler()
.
Static methods belong to the class and can be called without instantiating it. Non-static methods require an object instance of the class to be called.
Object-Oriented Programming (OOP) in PHP is a programming paradigm based on objects and classes. It supports concepts like encapsulation, inheritance, and polymorphism.
A class in PHP is a blueprint for creating objects. It defines properties (variables) and methods (functions) that the objects created from the class can use.
Inheritance allows a class to use the properties and methods of another class. The extends
keyword is used for this in PHP.
The final
keyword prevents a class from being inherited or a method from being overridden.
An interface defines a contract for classes. A class that implements an interface must define all the methods declared in the interface.
An abstract class cannot be instantiated and may contain abstract methods (without body) that must be implemented by child classes.
A constructor is a special function automatically called when an object is created. It is defined using __construct()
.
A destructor is a special function automatically called when an object is destroyed. It is defined using __destruct()
.
Both include a file only once during execution. require_once
stops the script with a fatal error if the file is not found, while include_once
only raises a warning.
Magic methods are special methods that start with double underscores, like __construct()
, __destruct()
, __get()
, and __set()
. They are invoked automatically based on certain conditions.
You can define a constant using define("NAME", "value")
or use the const
keyword inside classes.
public
methods/properties can be accessed anywhere, private
ones only within the class, and protected
within the class and its subclasses.
Traits are a mechanism for code reuse in PHP. They allow you to include methods in multiple classes without inheritance using the use
keyword.
array_merge()
merges arrays, while array_combine()
creates an array by using one array for keys and another for values.
explode()
splits a string into an array using a delimiter. Example: explode(",", "a,b,c")
returns ["a", "b", "c"]
.
implode()
joins array elements into a string. Example: implode("-", ["a", "b", "c"])
returns "a-b-c"
.
You can redirect a user using header("Location: page.php")
followed by exit()
to stop script execution.
Sessions are used to store user data across multiple pages, allowing for stateful interactions like login persistence.
Use session_start()
to begin the session, then session_unset()
and session_destroy()
to clear and destroy it.
$_FILES
is a superglobal used to upload files. It stores file information like name, type, size, temp location, and error status.
You can validate an email using filter_var($email, FILTER_VALIDATE_EMAIL)
. It returns the email if valid, or false if not.
mysql
is deprecated. mysqli
(MySQL Improved) supports prepared statements, multiple statements, and enhanced security.
Common error types include: Parse errors, Fatal errors, Warning errors, and Notice errors.
The @ symbol suppresses error messages for a specific expression. Use with caution, as it hides all errors that may be useful for debugging.
echo
can take multiple parameters and is slightly faster. print
can only take one parameter and returns 1, so it can be used in expressions.
A multidimensional array contains other arrays. Example:$arr = array(array("A", 1), array("B", 2));
==
checks for equality, while !=
(or <>
) checks for inequality in value.
is_array()
checks whether a variable is an array. in_array()
checks whether a value exists in an array.
strlen()
returns the length of a string in characters.
You can use the gettype()
function to find out the data type of a variable.
Quickly Find What You Are Looking For
Onlinetpoint is optimized for basic learning, practice and more. Examples are well checked and working examples available on this website but we can't give assurity for 100% correctness of all the content. This site under copyright content belongs to Onlinetpoint. You agree to have read and accepted our terms of use, cookie and privacy policy.