Contents
PHP Advance
PHP Superglobals
Introduction to Superglobal Variables in PHP
Superglobals are built-in array variables in PHP that allow developers to access important data about requests or scripts. These superglobals can be accessed globally from any part of your code, such as functions or classes, without requiring special declarations like global variables. They are especially useful for handling data transfer between pages, dealing with requests, and managing server information.
Here’s a list of the available superglobal variables in PHP:
$GLOBALS
$_SERVER
$_REQUEST
$_GET
$_POST
$_SESSION
$_COOKIE
$_FILES
$_ENV
Let’s take a closer look at some of these superglobals:
1. $GLOBALS
Superglobal :$GLOBALS
is used to access global variables from any part of the PHP script. PHP stores all global variables in the $GLOBALS
array, where the key is the variable name, and the value can be accessed.
Example:
Output:
30
2.$_SERVER
Superglobal:$_SERVER
holds information about headers, paths, and script locations. It provides valuable details about the server and the current script.
Example:
";
echo $_SERVER['SERVER_ADDR']; // Server IP
echo "
";
echo $_SERVER['HTTP_USER_AGENT']; // Browser details
echo "
";
echo $_SERVER['REQUEST_METHOD']; // HTTP method used
?>
Output:
/path/to/script.php
127.0.0.1
Mozilla/5.0 (your browser details)
GET
3.$_REQUEST
Superglobal: $_REQUEST
is a superglobal that collects data from forms, whether submitted using GET
or POST
. Although it’s versatile, developers often prefer using $_POST
or $_GET
for specific requests.
Example:
Output:
Hello, John
4.$_POST
Superglobal:$_POST
is used to collect data from forms when they are submitted using the POST method. The data is not visible in the URL, ensuring privacy and security.
Example:
Output:
Jane is 25 years old.
5. $_GET Superglobal: $_GET
is used to collect data from forms submitted using the GET method. Data sent this way is visible in the URL, making it less secure but useful in certain scenarios.
Example:
$_GET Example
Welcome, $name from $city!";
?>
Assuming URL
http://localhost/page.php?username=Alice&city=NewYork
Output:
Welcome, Alice from NewYork!
HTTP GET and POST Methods in PHP
Understanding HTTP GET and POST Methods in PHP
The Hypertext Transfer Protocol (HTTP) enables communication between clients (browsers) and servers. It follows a request-response model where the client submits an HTTP request, and the server responds with the necessary content and status information. In PHP, we frequently work with two primary HTTP request methods: GET and POST.
1. GET Method: Used to request data from a specified resource.
2. POST Method: Used to send data to the server for processing.
1. GET Method in PHP: The GET method sends data through the URL as query parameters. These parameters are key-value pairs separated by &
. The GET method is suitable for retrieving data and can be used to pass simple text information.
Example URL:
http://www.example.com/process.php?name=Alex&age=30
Here, name=Alex
and age=30
are the query parameters sent via GET.
Example: GET Method in PHP
";
echo "Your age is " . htmlspecialchars($_GET['age']);
exit();
}
?>
Output:
Hello, Alex
Your age is 30
In this example, the user enters their name and age, which is sent via the GET method. The data is displayed on the same page after submission.
Advantages of GET:
- The data is visible in the URL, making it easy to bookmark the page with query string values.
- GET requests can be cached and stored in browser history.
- They can also be bookmarked for future reference.
Disadvantages of GET:
- It’s unsuitable for sending sensitive data like passwords, as the information is exposed in the URL.
- The amount of data you can send via GET is limited by the URL length.
POST Method in PHP
The POST method sends data to the server within the HTTP request body, making it invisible in the URL. This method is commonly used when you need to send large amounts of data or sensitive information.
Example: POST Method in PHP
";
echo "Your height is " . htmlspecialchars($_POST['height']) . " cm.";
exit();
}
?>
Output:
Hello, John
Your height is 175 cm.
In this example, the user’s name and height are submitted via the POST method. The form data is securely processed, and the result is displayed on the same page.
Advantages of POST:
- Since the data isn’t visible in the URL, it’s more secure for handling sensitive information.
- The POST method allows sending large amounts of data, including files or binary data.
Disadvantages of POST:
- POST requests cannot be bookmarked since the data isn’t in the URL.
- POST requests are not cached or stored in browser history, making it harder to retrieve past form submissions.
PHP Regular Expressions
Regular expressions, often abbreviated as regex or regexes, are sequences of characters that define search patterns used for matching text. They are commonly employed in algorithms to match loosely defined patterns, helping with tasks like data validation, searching, and text manipulation. Regexes can be considered a mini programming language with a specific syntax that allows users to parse and manipulate text strings, making them invaluable tools in many programming contexts.
Regular expressions are powerful tools for working with string patterns, often used to efficiently match or extract certain sequences from text. PHP, being a popular open-source programming language, provides built-in support for regular expressions, just like many other programming languages. Different systems and languages may have their own syntax for regexes, but the basic concepts remain the same. Regexes are capable of working with very large text files or streams, and their applications are widespread across modern development environments.
Key Uses and Benefits of Regular Expressions:
1. Validation: Regexes can be used to validate user inputs such as email addresses, phone numbers, and IP addresses.
2. Searching and Matching: They offer efficient ways to search for and extract specific string patterns in large datasets.
3. Text Parsing: They are useful in parsing text files or streams to find patterns for further analysis or manipulation.
4. Development Efficiency: Using regex saves development time when performing pattern matching and text processing.
5. HTML Template Creation: Regexes help in recognizing tags and templates within HTML, allowing data to be substituted dynamically.
6. Form Validations: Ensuring fields like passwords meet strength requirements by using regex to check for required characters.
7. Other Uses: Regexes are used for browser detection, spam filtration, and keyword searching, among other applications.
Regular Expression Syntax and Examples:
Regular Expression | Matches |
---|---|
developers |
The string “developers” |
^developers |
Strings that begin with “developers” |
developers$ |
Strings that end with “developers” |
^developers$ |
The exact string “developers” |
[xyz] |
Any one of the characters: x, y, or z |
[a-z] |
Any lowercase letter |
[^A-Z] |
Any character that is not an uppercase letter |
`(png | jpeg)` |
[a-z]+ |
One or more lowercase letters |
^[a-zA-Z0-9]{3, }$ |
A word with at least three alphanumeric characters |
([mn])([op]) |
Matches: mo, mp, no, np |
[^a-zA-Z0-9] |
Any symbol other than letters or numbers |
`([A-Z]{2} | [0-9]{4})` |
Key Regex Operators:
Operator | Description |
---|---|
^ | Indicates the start of the string |
$ | Indicates the end of the string |
. | Matches any single character |
() | Groups expressions together |
[] | Matches any character within the brackets |
[^] | Matches any character not in the brackets |
- | Specifies a range (e.g., [a-z] for lowercase letters) |
` | ` |
? | Matches 0 or 1 of the preceding character |
* | Matches 0 or more of the preceding character |
+ | Matches 1 or more of the preceding character |
{n} | Matches exactly n occurrences |
{n,} | Matches at least n occurrences |
{n, m} | Matches between n and m occurrences |
\ | Escape character |
Special Character Classes:
Special Character | Meaning |
---|---|
\n | New line |
\r | Carriage return |
\t | Tab |
\v | Vertical tab |
\f | Form feed |
\xhh | Hexadecimal character |
Example Functions in PHP:
Function | Description |
---|---|
preg_match() | Searches for a pattern in a string and returns true if found |
preg_match_all() | Searches for all occurrences of a pattern and returns all matches |
preg_replace() | Searches and replaces occurrences of a pattern in a string |
preg_split() | Splits a string by a regex pattern |
preg_grep() | Searches for array elements that match a pattern |
PHP Example 1:
Output:
Valid name string
Example:
(.*)<\/b>/U";
$string = "Title: PHP Version: 7.4";
preg_match_all($regex, $string, $matches);
echo $matches[0][0] . "
" . $matches[0][1];
?>
Output:
PHP
7.4
Example:
Output:
Graduated in 2015
Metacharacters:
Metacharacter | Description | Example |
---|---|---|
. | Matches any single character except newline | /./ matches any character |
^ | Matches the start of a string | /^web/ matches “web” at the start |
$ | Matches the end of a string | /end$/ matches “end” at the end |
* | Matches zero or more occurrences | /do*/ matches “do”, “dog”, etc. |
+ | Matches one or more occurrences | /go+/ matches “go”, “good”, etc. |
\ | Escapes a metacharacter | /\./ matches the literal dot |
POSIX Regular Expressions:
Regex | Meaning |
---|---|
[0-9] | Matches any digit |
[a-z] | Matches any lowercase letter |
[A-Z] | Matches any uppercase letter |
[:lower:] | Matches any lowercase letter |
[:upper:] | Matches any uppercase letter |
[:alnum:] | Matches any alphanumeric character |
Quantifiers:
Quantifier | Meaning |
---|---|
a+ | Matches one or more occurrences of “a” |
a* | Matches zero or more occurrences of “a” |
a{2} | Matches exactly two occurrences of “a” |
a{2,} | Matches two or more occurrences of “a” |
a{2,5} | Matches between two and five occurrences of “a” |
^a | Matches “a” at the start of a string |
a$ | Matches “a” at the end of a string |
[^a-zA-Z] | Matches any character that is not a letter |
PHP Form Processing
Processing Forms in PHP
In this article, we will explore how to handle forms in PHP. HTML forms are designed to send user information to a server and return results to the browser. For instance, if you wish to collect visitor details on your website and send them positive messages, you can achieve this through form processing. The gathered information can be validated either on the client-side or server-side, and the final results are communicated back to the client via their web browser. To create an HTML form, you should utilize the <form>
tag.
Attributes of the Form Tag:
Attribute | Description |
---|---|
name or id | Specifies the name of the form, allowing for individual identification. |
action | Indicates the destination to which the form data will be sent upon submission. |
method | Defines the HTTP method to be used during form submission. Possible values include GET and POST . Using the GET method exposes the form data in the URL. The default method is GET . |
encType | Specifies the encoding type for the form data upon submission. |
novalidate | Instructs the server not to validate form data upon submission. |
Controls Used in Forms:
Form processing involves a variety of controls through which communication occurs between the client and the server. The controls typically found in forms are:
- Textbox: A textbox allows users to input single-line data, suitable for entries like names or search queries.
- Textarea: A textarea enables users to provide multi-line input, ideal for gathering information like addresses or messages.
- Dropdown: A dropdown (or combobox) lets users select a value from a predefined list.
- Radio Buttons: Radio buttons permit users to choose only one option from a specified set of options.
- Checkbox: Checkboxes allow users to select multiple options from a provided list.
- Buttons: Buttons are clickable elements used to submit the form.
Creating a Simple HTML Form:
All the aforementioned form controls can be created using the <input>
tag based on its type
attribute. In the following script, the form does not implement any event handling mechanism upon submission. Event handling refers to the processes executed during form submission, which can be managed using JavaScript or PHP. While JavaScript provides client-side validation, PHP is recommended for robust form processing.
HTML Code:
Simple Form Processing
Output:
Current file: /path/to/current/script.php
Form Validation:
Form validation ensures that users provide the required information. Basic validation can be implemented using HTML attributes. For example, in the script above, the email input has a type
of “email,” preventing incorrect entries. Each field in the form is marked with a required
attribute, prompting users to complete all fields before submission.
PHP Functions and Arrays Used in Form Processing:
isset()
: This function checks whether a variable or form control has a value.$_GET[]
: Retrieves information from form controls via parameters sent in the URL.$_POST[]
: Fetches data from form controls using the HTTP POST method.$_REQUEST[]
: Used to retrieve data when working with databases.
Form Processing Using PHP:
The above HTML code is revised to include the necessary functions and arrays for validation. The rewritten script checks all fields, and if no errors occur, it displays the submitted information in a table format.
Example:
Simple Form Processing
Form Processing with PHP
INPUT RECEIVED
";
echo "";
echo "";
echo "Parameter ";
echo "Value ";
echo "";
echo "";
echo "First Name ";
echo "".$firstname." ";
echo " ";
echo "";
echo "Last Name ";
echo "".$lastname." ";
echo " ";
echo "";
echo "Address ";
echo "".$address." ";
echo " ";
echo "";
echo "Email Address ";
echo "" .$emailaddress." ";
echo " ";
echo "";
echo "Password ";
echo "".$password." ";
echo " ";
echo "";
echo "Gender ";
echo "".$gender." ";
echo " ";
echo "
";
}
}
?>
Output:
INPUT RECEIVED
+------------------+------------------+
| Parameter | Value |
+------------------+------------------+
| First Name | John |
| Last Name | Doe |
| Address | 123 Main St |
| Email Address | john@example.com |
| Password | password123 |
| Gender | Male |
+------------------+------------------+
PHP Date and Time
Handling date and time is a common task in PHP, especially when managing database queries or web development tasks. PHP provides built-in functions for these operations, and we’ll discuss some of the most useful ones below.
PHP date()
Function:
The date()
function in PHP is used to convert a timestamp into a more human-readable format, allowing us to work with dates and times in a flexible way.
Why do we need the date()
function?
Dates and times in computers are stored as UNIX Timestamps, which are the number of seconds since the Unix epoch (January 1, 1970, 00:00:00 GMT). This raw format is not suitable for human interpretation, so PHP allows us to convert it into a readable format using the date()
function.
Syntax:
date(format, timestamp)
Explanation:
format
: Specifies the format of the output.timestamp
(optional): If not provided, the current date and time will be used.
Example: Here’s how you can use the date()
function to get today’s date:
Output:
Current date is: 23-10-2024
Formatting Options in the date()
Function:
The format
parameter allows us to specify how the date will be displayed. Below are some common formatting characters:
d
: Day of the month (01 to 31).D
: Abbreviated day name (Mon to Sun).m
: Month number (01 to 12).M
: Abbreviated month name (Jan to Dec).y
: Two-digit year (e.g., 24 for 2024).Y
: Four-digit year (e.g., 2024).
You can also include separators like hyphens (-
), dots (.
), slashes (/
), etc., to format the date as desired.
Example:
Output:
Date formats:
23/10/2024
23-10-2024
2024.10.23
Oct-23-2024/Wed
Time Formatting with date()
Function:
You can also use the date()
function to format the time string using the following characters:
h
: 12-hour format with leading zeros (01 to 12).H
: 24-hour format with leading zeros (00 to 23).i
: Minutes with leading zeros (00 to 59).s
: Seconds with leading zeros (00 to 59).a
: Lowercaseam
orpm
.A
: UppercaseAM
orPM
.
Example:
Output:
03:14:29 PM
23-Oct-2024 03:14:29 pm
PHP time()
Function:
The time()
function returns the current time as a Unix timestamp (the number of seconds since January 1, 1970, 00:00:00 GMT).
Example:
Output:
Current timestamp: 1729674869
Formatted time: October 23, 2024 03:14:29 PM
PHP mktime()
Function:
The mktime()
function is used to create a timestamp for a specified date and time. If no arguments are provided, it will return the current date and time.
Syntax:
mktime(hour, minute, second, month, day, year)
Example:
Output:
1729674330
PHP Date and Time
In this article, we will explore the include()
and require()
functions in PHP, understand how they impact code execution, and examine their differences and usage through examples. As you may know, PHP enables us to create reusable functions and elements that might be needed on multiple pages. Writing the same function across different pages is time-consuming and error-prone. This repetition can be avoided using the concept of file inclusion, which allows you to insert external files—containing text or code—into a program, saving time and effort. If you need to update the code later, modifying the source file will automatically update all the files that include it. PHP offers two key functions for this purpose:
1. include() function
2. require() function
We will explore both of these functions, their uses, and their differences through examples.
PHP include()
Function:
The include()
function allows us to include the contents of a file within another PHP file. It copies the contents of the specified file into the location where the include()
function is called, before the server executes the rest of the script.
Example: Using the include()
function in PHP
Now, we can include this file in another PHP file, such as index.php
:
File has been included successfully.";
?>
PHP require()
Function:
The require()
function works similarly to the include()
function. It also copies the contents of the specified file into the location where it is called.
Example: Using the require()
function in PHP
We can include this file using the require()
function in another PHP file:
File has been required successfully.";
?>
Difference between include()
and require()
functions:
While both include()
and require()
perform the same task of file inclusion, there is one key difference in how they handle errors. This difference becomes evident when an error arises, such as a missing file.
Example 1: Using include()
when a file is missing:
This message is displayed even if the file is missing.";
?>
Output:
Warning: include(missing_file.php): Failed to open stream: No such file or directory in [file path] on line X
Warning: include(): Failed opening 'missing_file.php' for inclusion in [file path] on line X
This message is displayed even if the file is missing.
PHP File Handling
File handling in PHP allows you to create, open, read, write, delete, and manage files on a server. It’s especially useful when you need to store data persistently or handle file uploads by users. PHP provides a variety of built-in functions that simplify and secure file handling tasks.
Common File Handling Functions in PHP
fopen()
– Opens a file.fclose()
– Closes a file.fread()
– Reads data from a file.fwrite()
– Writes data to a file.file_exists()
– Checks if a file exists.unlink()
– Deletes a file.
What is File Handling in PHP?
File handling refers to the process of working with files on the server, including reading, writing, creating, or deleting files. It is crucial for applications requiring data storage and retrieval, such as logging systems, user-generated content, or file uploads.
Opening and Closing Files
Before performing operations like reading or writing to a file, it needs to be opened using the fopen()
function, which returns a file pointer resource. After the file operations are done, the file should be closed using fclose()
to free system resources.
File Modes in PHP
Files can be opened in several modes, such as:
"w"
– Opens the file for writing. If the file doesn’t exist, a new one is created. If it exists, the contents will be erased."r"
– Opens the file for reading only."a"
– Opens the file for writing, appending data to the end. Existing data is preserved."w+"
– Opens the file for both reading and writing. If it doesn’t exist, a new one is created. If it exists, its contents are erased."r+"
– Opens the file for both reading and writing."a+"
– Opens the file for both writing and reading, appending data to the end. If the file doesn’t exist, a new one is created."x"
– Creates a new file for writing only.
Reading from Files
There are two primary ways to read the contents of a file in PHP:
1. Reading the Entire File: You can use the fread()
function or file_get_contents()
to read the whole content of a file.
2. Reading a File Line by Line: The fgets()
function allows reading a file line by line.
";
}
fclose($file);
}
?>
3. Writing to Files: To write data to a file, you can use the fwrite()
function, which writes to an open file in the specified mode.
4. Deleting Files: To delete a file in PHP, use the unlink()
function.
File opened successfully!
2. Reading the entire file:
(Contents of example.txt displayed here)
3. Reading the file line by line:
(Each line of example.txt is displayed with
between lines)
4. Writing to a file: No output. The contents of example.txt
will be updated with the text “Hello, PHP file handling!”.
5. Deleting a file:
File deleted successfully!
PHP Uploading File
Approach: To execute the PHP script, you’ll need a server environment. Ensure you have either XAMPP or WAMP installed on your machine for testing purposes.
HTML Code Snippet: Here’s an HTML code example for creating a file upload form. The enctype='multipart/form-data'
is an encoding type that allows files to be sent through a POST method. Without this, files cannot be uploaded through the form.
upload.html
:
File Upload
In this form, we use the enctype
attribute to ensure that the form can handle file uploads. The input field name fileToUpload
will be used later in our PHP script to access the uploaded file.
PHP File Upload Script: Now let’s create the PHP script to manage the file upload.
upload-handler.php
:
"application/pdf", "docx" => "application/vnd.openxmlformats-officedocument.wordprocessingml.document", "txt" => "text/plain");
$file_name = $_FILES["fileToUpload"]["name"];
$file_type = $_FILES["fileToUpload"]["type"];
$file_size = $_FILES["fileToUpload"]["size"];
// Extract file extension
$file_extension = pathinfo($file_name, PATHINFO_EXTENSION);
// Check if the file extension is allowed
if (!array_key_exists($file_extension, $allowed_extensions)) {
die("Error: Please upload a valid file format.");
}
// Check file size (max 3MB)
$maxsize = 3 * 1024 * 1024;
if ($file_size > $maxsize) {
die("Error: File size exceeds the 3MB limit.");
}
// Verify file MIME type
if (in_array($file_type, $allowed_extensions)) {
// Check if the file already exists
if (file_exists("uploads/" . $file_name)) {
echo "Error: " . $file_name . " already exists!";
} else {
// Move the file to the uploads directory
move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], "uploads/" . $file_name);
echo "File uploaded successfully!";
}
} else {
echo "Error: Invalid file type.";
}
} else {
echo "Error: " . $_FILES["fileToUpload"]["error"];
}
}
?>
In this script, we first check if the form was submitted using the POST method. Then, we access the uploaded file using the $_FILES
array to retrieve the file name, size, and type. After that, we validate the file type and size. If the file passes the checks, we move it from its temporary location to the uploads
folder on the server.
Output:
When the form is submitted, the following scenarios could occur:
1. File Uploaded Successfully:
File uploaded successfully!
2. File Size Exceeds Limit:
Error: File size exceeds the 3MB limit.
3. Invalid File Type:
Error: Please upload a valid file format.
4. File Already Exists:
Error: filename.docx already exists!
5. General Upload Error:
Error: (error code)
PHP Cookies
A cookie in PHP is a small data file, typically 4KB in size, that a web server saves on a user’s computer. Cookies are mainly used to track user information, such as usernames, to personalize web experiences when the user revisits the site. Cookies can only be accessed by the domain that created them, and while they are usually set using HTTP headers, they can also be created using JavaScript.
Setting a Cookie in PHP:
To create a cookie in PHP, you use the setcookie()
function. This function needs to be called before any output is generated by the script; otherwise, the cookie won’t be set.
Syntax:
setcookie(name, value, expire, path, domain, security);
Parameters:
- Name: The name of the cookie.
- Value: The value to be stored in the cookie.
- Expire: The expiration timestamp for the cookie. After this time, the cookie is no longer available.
- Path: Specifies the path on the server where the cookie will be available.
- Domain: Defines the domain where the cookie is accessible.
- Security: Indicates if the cookie should only be sent over secure HTTPS connections.
Operations on Cookies in PHP:
1. Creating Cookies: This example creates a cookie named User_Preference
with a value of "Dark Mode"
, which will expire after 3 days.
Note: You may need to reload the page to see the cookie's value.
Output:
Cookie has been set.
Note: Only the name
parameter is mandatory in setcookie()
. You can leave other parameters blank by providing an empty string (""
).
2. Checking if a Cookie is Set: It’s a good practice to check if a cookie exists before trying to access it. You can use the isset()
function to verify whether a cookie is set.
Example:
Note: Reload the page to check the cookie's value.
Output:
User preference is set to Dark Mode
3. Accessing Cookie Values: You can retrieve a cookie’s value using PHP’s $_COOKIE
superglobal array. This array holds all the cookies sent by the user’s browser in the current request.
Example:
Note: Reload the page to access the cookie value.
Output:
The current user preference is: Dark Mode
4. Deleting Cookies: You can delete a cookie by calling setcookie()
again but setting the expiration time to a point in the past.
Example:
Note: Reload the page to ensure the cookie is deleted.
Output:
Cookie has been deleted.
PHP Sessions
In general, a session refers to a period of communication between two entities. In PHP, sessions are used to store user data on the server rather than on the client side, offering a more secure way to manage user-related information. Each user in a session-based environment is assigned a unique identifier known as a Session ID (SID). The SID helps link users to their session data stored on the server, such as posts, emails, and other personal information.
Why are Sessions Better than Cookies?
While cookies are also used to store user-related data, they come with security concerns. Cookies are stored on the user’s computer, making them vulnerable to tampering. Attackers can easily modify cookie content, which may lead to malicious data being injected into the application. Moreover, cookies can slow down website performance, as they send user data back to the server every time the user loads a page. Each time the browser makes a request, all cookie data for that site is included in the request.
Steps Involved in PHP Sessions:
1. Starting a Session: To initiate a session, the session_start()
function is used. This function starts a new session or resumes an existing one, and also generates a new session ID.
Example:
2. Storing Session Data: Session data can be stored as key-value pairs using the $_SESSION[]
superglobal array. This data will persist across different pages during the session.
Example:
3. Accessing Session Data: To retrieve session data, you must first call session_start()
and then use the key from the $_SESSION
array.
Example:
';
echo 'The student\'s ID is: ' . $_SESSION["StudentID"] . '
';
?>
Output:
The student's name is: Rahul
The student's ID is: 101
4. Deleting Specific Session Data: To remove specific session data, you can use the unset()
function with the particular session variable.
Example:
Output:
Coding is challenging!
Implementing callback in PHP
In PHP, a callback is essentially a reference to a function that can be called later. A callback variable (or callable) can represent various types of functions such as normal functions, object methods, or static methods in classes. Below are a few ways to implement a callback in PHP:
Standard Callback:
In PHP, normal functions can be invoked through the call_user_func()
function, where the argument is simply the function’s name as a string.
Example:
Output:
Hello World
Static Class Method Callback:
Static methods in classes can also be invoked using call_user_func()
. The argument in this case is an array where the first element is the class name and the second element is the method name.
Example:
Output:
Child Class Method
Child Class Method
Base Class Method