php_notes
php_notes
PHP is an open-source, interpreted, and object-oriented scripting language that can be executed at the
server-side. PHP is well suited for web development. Therefore, it is used to develop web applications (an
application that executes on the server and generates the dynamic page.).
PHP stands for a recursive acronym PHP: Hypertext Preprocessor. PHP is the world’s most popular server-
side programming language. PHP was created by Rasmus Lerdorf in 1994 but appeared in the market in 1995.
Its latest version PHP 8.2.8, released on July 4th, 2023.
PHP is a server-side scripting language that is embedded in HTML. PHP is a cross-platform language, capable
of running on all major operating system platforms and with most of the web server programs such as
Apache, IIS, lighttpd and nginx.
Features Of PHP
1. Server-Side Scripting: PHP runs on the web server, allowing for dynamic content generation and
interaction with databases and other resources. This keeps sensitive logic and data processing on the server-
side, improving security and performance.
2. Open Source and Free: PHP is an open-source language, freely available for anyone to use and modify.
This fosters a large community of developers contributing to its ongoing development and vast amount of
available resources.
3. Ease of Use: PHP has a relatively simple syntax, making it easier to learn compared to some other
programming languages. This allows developers to get started quickly and build basic web applications with
minimal effort.
4. Object-Oriented Programming (OOP): While not mandatory, PHP supports object-oriented programming
principles. This allows for better code organization, reusability, and maintainability when building complex
applications.
5. Rich Standard Library: PHP comes with a large collection of built-in functions for common tasks like
database interaction, string manipulation, user input validation, and more. This reduces the need for
developers to write repetitive code
6. Database Integration: PHP seamlessly integrates with various popular databases like MySQL, PostgreSQL,
and Oracle. This allows websites to store and retrieve information dynamically, making them more
interactive and data-driven.
1
7. Security Features: While security ultimately depends on the developer's practices, PHP offers features
like input validation and user authentication mechanisms to help prevent common web security
vulnerabilities.
8. Flexibility and Scalability: PHP can be used for a wide range of projects, from simple web pages to
complex e-commerce applications and content management systems (CMS). It can also scale well to handle
increasing website traffic and user demands.
History of PHP
* A major turning point with features like extensibility, object-oriented programming, and consistent syntax.
* Powered by the new Zend Engine for increased performance and modularity.
* Expanded capabilities with enhanced web server support, HTTP sessions, and secure user input handling.
2
* Marked a significant step forward in PHP's maturity and functionality.
* Attempted major changes like Unicode support but encountered technical issues.
* Delivered a significant performance boost, making PHP faster and more efficient.
* Introduced modern features like strict typing declarations, anonymous functions, and the null coalescing
operator.
* A major leap forward in both performance and embracing modern language features.
* Introduced Just-in-Time (JIT) compilation for even faster execution, union types, and match expressions.
Advantages of PHP
PHP is an open-source language, which means it is free to use by developers. It is also one of the oldest
scripting languages that are used by many popular brands. It does not require any fee to use frameworks,
libraries, and databases.
PHP has a vast set of tutorials, resources, and other insights that anyone can use to learn this language
effortlessly. At the same time, the Graphical User Interface (GUI) made this language easy to use.
3. Platform Independent
PHP language can be easily downloaded and is compatible with various platforms and operating systems.
Being the interpreted language, it executes the code itself, making it platform-independent.
4. Community Support
Even though it is an easy-to-use language, anyone with knowledge of C programming can learn and use it.
However, there will be times when you need help from experts in this field. In that case, you can ask your
queries on forums and various other platforms that largely contribute to the advancement of PHP.
3
5. Scalability
If you want to develop a website, you must be looking for ways to enhance your business. Therefore, in the
long run, you will add new features and functionalities to your web application. With the help of this scripting
language, you can complete this task. Not only can you focus on faster loading websites but integrate with
other technologies to enhance the performance.
Disadvantages of PHP
1. Limited Customization
You can create an intuitive website and web application using PHP, and it allows customization and
integration to some extent. However, if your project demands the incorporation of technologies like machine
learning, AR/VR, big data, etc., you might need to find another language to use.
Being an open-source language, the ASCII text file is open for anyone to see. Hence, general people can see
the logic and even bugs in your code, making it easier for them to manipulate it. Hence, your website
becomes vulnerable to XSS and SQL injection attacks. Also, there is no default security mechanism in PHP,
leading to security concerns.
4. Less Versatility
With PHP, you get less opportunity to make modifications to the website. Therefore, you might not be able
to keep up with the required creative challenge of a website. Also, as compared to other languages, PHP is
less effective and slower to work with.
The simple syntax makes PHP a perfect solution for building a dynamic website. However, with restrained
debugging opportunities, it does not handle errors well. Since the debugging tools do not identify errors
properly, debugging is a difficult task as compared to other programming languages. Hence, developers and
business owners consider it to be more prone to security concerns.
“Server-side scripting is a programming technique for creating code that may run software on the server
side. In other words, server-side scripting is any scripting method that may operate on a web server. At the
server end, actions such as website customization, dynamic changes in website content, response creation
to user requests, database access, and many more are carried out.Server-side scripting creates a
communication channel between a server and a client.”
4
The server-side is made up of three parts: the database, the server, the APIs, and the backend web software
written in the server-side scripting language. When a browser requests a page with server-side scripting, the
web server evaluates the script before delivering the page to the browser. In this case, script processing may
entail collecting information from a database, performing simple computations, or selecting the relevant
material to be shown on the client end. The output is provided to the web browser when the script is
processed. The web server hides the scripts from the end user until the content is delivered, making the data
and source code safer.
Static sites
The diagram below shows a basic web server architecture for a static site (a static site is one that returns the
same hard-coded content from the server whenever a particular resource is requested). When a user wants
to navigate to a page, the browser sends an HTTP "GET" request specifying its URL.
The server retrieves the requested document from its file system and returns an HTTP response containing
the document and a success status (usually 200 OK). If the file cannot be retrieved for some reason, an error
status is returned (see client error responses and server error responses).
Dynamic sites
A dynamic website is one where some of the response content is generated dynamically, only when needed.
On dynamic website HTML pages are normally created by inserting data from a database into placeholders
in HTML templates (this is a much more efficient way of storing large amounts of content than using static
websites).A dynamic site can return different data for a URL based on information provided by the user or
stored preferences and can perform other operations as part of returning a response (e.g. sending
notifications).
Most of the code to support a dynamic website must run on the server. Creating this code is known as
"server-side programming" (or sometimes "back-end scripting").
5
The diagram below shows a simple architecture for a dynamic website. As in the previous diagram, browsers
send HTTP requests to the server, then the server processes the requests and returns appropriate HTTP
responses.
Requests for static resources are handled in the same way as for static sites (static resources are any files
that don't change — typically: CSS, JavaScript, Images, pre-created PDF files, etc.).
Requests for dynamic resources are instead forwarded (2) to server-side code (shown in the diagram as a
Web Application). For "dynamic requests" the server interprets the request, reads required information from
the database (3), combines the retrieved data with HTML templates (4), and sends back a response
containing the generated HTML (5,6).
Code running in the browser is known as client-side code and is primarily concerned with improving the
appearance and behaviour of a rendered web page. This includes selecting and styling UI components,
creating layouts, navigation, form validation, etc. By contrast, server-side website programming mostly
involves choosing which content is returned to the browser in response to requests. The server-side code
handles tasks like validating submitted data and requests, using databases to store and retrieve data and
sending the correct data to the client as required.
Server-side code can be written in any number of programming languages — examples of popular server-
side web languages include PHP, Python, Ruby, C#, and JavaScript (NodeJS). The server-side code has full
access to the server operating system and the developer can choose what programming language (and
specific version) they wish to use.
6
Developers typically write their code using web frameworks. Web frameworks are collections of functions,
objects, rules and other code constructs designed to solve common problems, speed up development, and
simplify the different types of tasks faced in a particular domain.
Again, while both client and server-side code use frameworks, the domains are very different, and hence so
are the frameworks. Client-side web frameworks simplify layout and presentation tasks while server-side
web frameworks provide a lot of "common" web server functionality that you might otherwise have to
implement yourself (e.g. support for sessions, support for users and authentication, easy database access,
templating libraries, etc.).
Server-side programming is very useful because it allows us to efficiently deliver information tailored for
individual users and thereby create a much better user experience.
1. Companies like Amazon use server-side programming to construct search results for products, make
targeted product suggestions based on client preferences and previous buying habits, simplify purchases,
etc.
2. Banks use server-side programming to store account information and allow only authorized users to view
and make transactions. Other services like Facebook, Twitter, Instagram, and Wikipedia use server-side
programming to highlight, share, and control access to interesting content.
Some of the common uses and benefits of server-side programming are listed below.
Server-side programming allows us to instead store the information in a database and dynamically construct
and return HTML and other types of files (e.g. PDFs, images, etc.). It is also possible to return data (JSON,
XML, etc.) for rendering by appropriate client-side web frameworks (this reduces the processing burden on
the server and the amount of data that needs to be sent).
The server is not limited to sending information from databases, and might alternatively return the result of
software tools, or data from communications services. The content can even be targeted for the type of
client device that is receiving it.
Servers can store and use information about clients to provide a convenient and tailored user experience.
For example, many sites store credit cards so that details don't have to be entered again. Sites like Google
Maps can use saved or current locations for providing routing information, and search or travel history to
highlight local businesses in search results.
7
A deeper analysis of user habits can be used to anticipate their interests and further customize responses
and notifications, for example providing a list of previously visited or popular locations you may want to look
at on a map.
Server-side programming allows sites to restrict access to authorized users and serve only the information
that a user is permitted to see.Real-world examples include social-networking sites which allow users to
determine who can see the content they post to the site, and whose content appears in their feed.
Server-side programming allows developers to make use of sessions — basically, a mechanism that allows a
server to store information associated with the current user of a site and send different responses based on
that information.
This allows, for example, a site to know that a user has previously logged in and display links to their emails
or order history, or perhaps save the state of a simple game so that the user can go to a site again and carry
on where they left
To Install And Configure PHP On A Windows System Using XAMPP (Which Includes Apache, Mysql, PHP,
And Perl), Follow These Steps:
1. Download XAMPP
2.Install XAMPP
- Choose the components you want to install, including Apache, MySQL, PHP, and other optional
components.
- Start the Apache and MySQL services by clicking the "Start" button next to their names.
8
4. Testing Apache
- If Apache is running properly, you should see the XAMPP dashboard or a page indicating that Apache is
installed and running.
5. Configure PHP
- Locate the `php.ini` configuration file inside the XAMPP installation directory (usually
`C:\xampp\php\php.ini`).
- Make any necessary configuration changes in the `php.ini` file. Common configurations include settings
for error reporting, timezone, and file upload limits.
6. Testing PHP
- Create a new PHP file (e.g., `test.php`) in the `htdocs` directory within the XAMPP installation directory
(usually `C:\xampp\htdocs`).
- Open `test.php` in a text editor and add the following PHP code:
```php
<?php
phpinfo();
?>
```
- If PHP is configured correctly, you should see a page displaying PHP configuration information.
XAMPP provides a convenient way to set up a local development environment with PHP on Windows. It
includes all the necessary components for web development, allowing you to start building and testing PHP-
based applications quickly and easily.it.
9
Embedding PHP in HTML: Powering Dynamic Webpages
One of the core strengths of PHP is its ability to seamlessly integrate with HTML, the language that forms the
static structure and content of webpages. This combination allows you to create dynamic webpages that
adapt and respond based on various factors. Here's a breakdown of embedding PHP in HTML and why it's
beneficial:
1) Mixing Code: You can embed PHP code directly within your HTML files. To distinguish it from regular
HTML, PHP code is enclosed within special tags: `<?php ?>`.
2) Server-Side Execution: When a user requests a webpage containing PHP code, the web server doesn't
send the raw HTML straight to the browser. Instead, it first executes the PHP code on the server. Keeps
sensitive logic and data processing on the server, improving security. User passwords or credit card
information never reach the user's browser.
3) Dynamic Content Generation: The executed PHP code can perform various actions like fetching data
from databases, handling user input, or performing calculations. It then generates the final HTML content
based on these actions. Lets you create webpages that change based on user input, database
information, or other factors, making them more interactive and engaging. Imagine a login page that
personalizes greetings based on the username.
4) Data Integration: Allows you to connect to databases and display information relevant to each user or
request. Think about an e-commerce website showing product details based on user searches.
5) Conditional Logic: Enables you to show or hide content based on certain conditions, personalizing the
user experience. For example, displaying a "Welcome Back" message for logged-in users.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
</head>
10
<body>
<p>The current date and time is: <?php echo date('Y-m-d H:i:s'); ?></p>
</body>
</html>
PHP Opening Tag: The <?php tag denotes the beginning of a PHP code block.
date() Function: The date() function is called with the format 'Y-m-d H:i:s' to retrieve the current date and
time in the specified format (Year-Month-Day Hour:Minute:Second).
Variable Assignment: The result of the date() function call is stored in the variable $currentDateTime.
Output: The echo statement outputs the current date and time along with the text "The current date and
time is: ".
When this PHP code is executed, it will dynamically generate the current date and time and output it as part
of the text "The current date and time is: " followed by the formatted date and time string.
11
HTML and Whitespaces
Whitespace is any string of text composed only of spaces, tabs or line breaks (to be precise, CRLF sequences,
carriage returns or line feeds). These characters allow you to format your code in a way that will make it
easily readable by yourself and other people. In fact, much of our source code is full of these whitespace
characters, and we only tend to get rid of it in a production build step to reduce code download sizes.
HTML largely ignores whitespace?
In the case of HTML, whitespace is largely ignored — whitespace in between words is treated as a single
character, and whitespace at the start and end of elements and outside elements is ignored. Take the
following minimal example:
12
<body>
<h1>Header</h1>
<p>Paragraph</p>
</body>
</html>
13
raisePrices($inventory,$inflation,$costOfLiving,$greed);
You can take advantage of this flexible formatting to make your code more readable (by lining up
assignments, indenting, etc.). Some lazy programmers take advantage of this freeform formatting and create
completely unreadable code—this is not recommended.
14
/*
This is a multi-line comment in PHP.
It can span multiple lines and is ignored by the PHP interpreter.
Multi-line comments are useful for providing detailed explanations or
commenting out large blocks of code temporarily.
*/
echo "Hello, World!";
?>
15
The below code will display an HTML form containing two input fields and a submit button. In this HTML
form, we used the method = "get" to submit the form data.
1. <html>
2. <body>
3. <form action = "gettest.php" method = "GET">
4. Username: <input type = "text" name = "username" /> <br>
5. Blood Group: <input type = "text" name = "bloodgroup" /> <br>
6. <input type = "submit" />
7. </form>
8. </body>
9. </html>
Create php file, which will accept the data sent by HTML form.
1. <html>
2. <body>
3. Welcome <?php echo $_GET["username"]; ?> </br>
4. Your blood group is: <?php echo $_GET["bloodgroup"]; ?>
5. </body>
6. </html>
When the user will click on Submit button after filling the form, the URL sent to the server could look
something like this:
localhost/gettest.php?username=Harry&bloodgroup=AB-
The output will look like the below output:
Welcome Harry
Your blood group is: AB-
16
o GET requests are always remained in the browser history.
Disadvantages of GET Method
o The GET method should not be used while sending any sensitive information.
o A limited amount of data can be sent using method = "get". This limit should not exceed 2048
characters.
o For security reasons, never use the GET method to send highly sensitive information like username
and password, because it shows them in the URL.
o The GET method cannot be used to send binary data (such as images or word documents) to the
server.
POST method
Similar to the GET method, the POST method is also used to submit the HTML form data. But the data
submitted by this method is collected by the predefined superglobal variable $_POST instead of $_GET.
Unlike the GET method, it does not have a limit on the amount of information to be sent. The information
sent from an HTML form using the POST method is not visible to anyone.
For Example
1. localhost/posttest.php
Note that the "post" method is more secure than the "get" method because the data sent using the POST
method is not visible to user.
With the help of an example, let's understand how the POST method works-
Example
The below code will display an HTML form containing two input fields and a submit button. In this HTML
form, we used the method = "post" to submit the form data.
file: test2.html
1. <html>
2. <body>
3. <form action = "posttest.php" method = "post">
4. Username: <input type = "text" name = "username" /> <br>
5. Blood Group: <input type = "text" name = "bloodgroup" /> <br>
6. <input type = "submit" />
7. </form>
8. </body>
9. </html>
17
Now create posttest.php file to accept the data sent by HTML form.
file: posttest.php
1. <html>
2. <body>
3. Welcome <?php echo $_POST["username"]; ?> </br>
4. Your blood group is: <?php echo $_POST["bloodgroup"]; ?>
5. </body>
6. </html>
When the user will click on Submit button after filling the form, the URL sent to the server could look
something like this:
localhost/posttest.php
The output will look like the below output:
Welcome Harry
Your blood group is: O+
18
$_REQUEST variable
The $_REQUEST variable is a superglobal variable, which can hold the content of both $_GET and $_POST
variable. In other words, the PHP $_REQUEST variable is used to collect the form data sent by either GET or
POST methods. It can also collect the data for $_COOKIE variable because it is not a method-specific variable.
You can access this data with the $_REQUEST keyword followed by variable name
$_REQUEST['firstname']
<html>
<body>
<form method="post" action="demo_request.php">
Name: <input type="text" name="fname">
<input type="submit">
</form>
</body>
</html>
When a user clicks the submit button, the form data is sent to a PHP file specified in the action attribute of
the <form> tag.In the action file we can use the $_REQUEST variable to collect the value of the input field.
PHP file
$name = $_REQUEST['fname'];
echo $name;
19
In the example below we have put the HTML form and PHP code in the same PHP file.We have also added
some extra lines for security.
<html>
<body>
<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
Name: <input type="text" name="fname">
<input type="submit">
</form>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = htmlspecialchars($_REQUEST['fname']);
if (empty($name)) {
echo "Name is empty";
} else {
echo $name;
}
}
?>
</body>
</html>
<html>
<body>
<a href="demo_phpfile.php?subject=PHP&web=W3schools.com">Test $GET</a>
</body>
</html>
When a user clicks the link, the query string data is sent to demo_phpfile.php.
In the PHP file we can use the $_REQUEST variable to collect the value of the query string.
Example
The PHP file demo_phpfile.php:
20
<html>
<body>
<?php
echo "Study " . $_REQUEST['subject'] . " at " . $_REQUEST['web'];
?>
</body>
</html>
21
<?php
$x = 7;
// Define a conditional statement
if ($x == 5) {
echo "x is equal to 5.";
}
// Define a function
function add($a, $b)
{
return $a + $b;
} ?>
Data Types
PHP provides eight types of values, or data types. Four are scalar (single-value) types: integers, floating-point
numbers, strings, and Booleans. Two are compound (collection) types: arrays and objects. The remaining
two are special types: resource and NULL. Numbers
1)Integers: integers are whole numbers, such as 1, 12, and 256. The range of acceptable values varies
according to the details of your platform but typically extends from −2,147,483,648 to +2,147,483,647.
Integer literals can be written in decimal, octal, or hexadecimal. Decimal values are represented by a
sequence of digits, without leading zeros. The sequence may begin with a plus (+) or minus (−) sign. If there
is no sign, positive is assumed. Examples of decimal integers include the following:
1998,−641,+33
Octal numbers consist of a leading 0 and a sequence of digits from 0 to 7. Like decimal numbers, octal
numbers can be prefixed with a plus or minus. Here aresome example octal values and their equivalent
decimal values:
0755 // decimal 493
+010 // decimal 8
Hexadecimal values begin with 0x, followed by a sequence of digits (0–9) or letters (A–F). The letters can be
upper-or lowercase but are usually written in capitals. Like decimal and octal values, you can include a sign
in hexadecimal numbers:
0xFF // decimal 255
0x10 // decimal 16
-0xDAD1 // decimal −56017
Binary numbers begin with 0b, followed by a sequence of digits (0 and 1). Like other values, you can include
a sign in binary numbers:
0b01100000 // decimal 1
0b00000010 // decimal 2
22
Use the is_int() function (or its is_integer() alias) to test whether a value is
an integer:
if (is_int($x)) {
// $x is an integer
}
2) Floating-Point Numbers
Floating-point numbers (often referred to as real numbers) represent numeric values with decimal digits.
Like integers, their limits depend on your machine’s details Usually, this allows numbers between 1.7E−308
and 1.7E+308 with 15 digits of accuracyPHP recognizes floating-point numbers written in two different
formats. There’s the one we all use every day:
3.14,0.017,-7.1
but PHP also recognizes numbers in scientific notation:
0.314E1 // 0.314*10^1, or 3.14
17.0E-3 // 17.0*10^(-3), or 0.017
Floating-point values are only approximate representations of numbers. For example, on many systems 3.5
is represented as 3.4999999999. This means you must take care to avoid writing code that assumes floating-
point numbers are represented completely accurately, such as directly comparing two floating-point values
using ==. The normal approach is to compare to several decimal places:
if (intval($a * 1000) == intval($b * 1000)) {
// numbers equal to three decimal places
}
Use the is_float() function (or its is_real() alias) to test whether a value is a floating-point number:
if (is_float($x)) {
// $x is a floating-point number
}
3)Strings: PHP includes core-level support for creating and manipulating strings. A string is a sequence of
characters of arbitrary length. String literals are delimited by either single or double quotes:
'big dog'
"fat hog"
Variables are expanded (interpolated) within double quotes, while within single quotes they are not:
$name = "Guido";
echo "Hi, $name\n";
echo 'Hi, $name';
Hi, Guido
Hi, $name
23
Double quotes also support a variety of string escapes, as listed. Escape sequence Character represented
\" Double quotes
\n Newline
\r Carriage return
\t Tab
\\ Backslash
\$ Dollar sign
\{ Left brace
\} Right brace
\[ Left bracket
\] Right bracket
To test whether two strings are equal, use the == (double equals) comparison
operator:
if ($a == $b) {
echo "a and b are equal"
}
Use the is_string() function to test whether a value is a string:
if (is_string($x)) {
// $x is a string
}
4) Booleans
A Boolean value represents a “truth value”—it says whether something is true or not. Like most
programming languages, PHP defines some values as true and others as false. Truth and falseness determine
the outcome of conditional code
In PHP, the following values all evaluate to false:
The keyword false
The integer 0
The floating-point value 0.0
The empty string ("") and the string "0"
An array with zero elements
An object with no values or functions
The NULL value
PHP provides true and false keywords for clarity:
24
$x = 5; // $x has a true value
$x = true; // clearer way to write it
$y = ""; // $y has a false value
$y = false; // clearer way to write it
Use the is_bool() function to test whether a value is a Boolean:
if (is_bool($x)) {
// $x is a Boolean
}
5)Arrays
In PHP, an array is a data structure that can hold multiple values under a single variable name. Arrays are
incredibly versatile and commonly used for storing and manipulating collections of data. PHP supports
several types of arrays, including indexed arrays, associative arrays, and multidimensional arrays.
1. Indexed Arrays:
An indexed array is a simple list of values, where each value is assigned a numeric index starting from zero.
You can create an indexed array using the `array()` function or using shorthand square bracket syntax (`[]`)
since PHP 5.4.Elements of an indexed array are accessed using numeric indices.
// Creating an indexed array
$colors = array("Red", "Green", "Blue");
// Accessing elements of an indexed array
echo $colors[0]; // Output: Red
echo $colors[1]; // Output: Green
echo $colors[2]; // Output: Blue
2. Associative Arrays:
An associative array is a collection of key-value pairs, where each key is associated with a value. You can
create an associative array using the `array()` function with key-value pairs or using shorthand square bracket
syntax (`[]`) .Elements of an associative array are accessed using their keys.
// Creating an associative array
$person = array("name" => "John", "age" => 30, "city" => "New York");
// Accessing elements of an associative array
echo $person["name"]; // Output: John
echo $person["age"]; // Output: 30
25
echo $person["city"]; // Output: New York
3. Multidimensional Arrays:
A multidimensional array is an array that contains one or more arrays as its elements. You can create
multidimensional arrays by nesting arrays inside arrays.Elements of multidimensional arrays are accessed
using multiple indices corresponding to each level of nesting.
// Creating a multidimensional array
$matrix = array(
array(1, 2, 3),
array(4, 5, 6),
array(7, 8, 9)
);
// Accessing elements of a multidimensional array
echo $matrix[0][0]; // Output: 1
echo $matrix[1][1]; // Output: 5
echo $matrix[2][2]; // Output: 9
```
6)Objects
PHP also supports object-oriented programming (OOP). OOP promotes clean modular design, simplifies
debugging and maintenance, and assists with code reuse. Classes are the building blocks of object-oriented
design. A class is a definition of a structure that contains properties (variables) and methods (functions).
Classes are defined with the class keyword:
class Person{
public $name = '';
function name ($newname = NULL){
if (!is_null($newname)) {
$this->name = $newname;
}
return $this->name;
}
}
Once a class is defined, any number of objects can be made from it with the new keyword, and the object’s
properties and methods can be accessed with the -> construct:
26
echo "Hello, {$ed->name}\n";
$tc = new Person;
$tc->name('Mister');
echo "Look out Above {$tc->name}\n";
Hello, Edison
Look out Above Mister
Use the is_object() function to test whether a value is an object:
if (is_object($x)) {
// $x is an object
}
7)Resources
Many modules provide several functions for dealing with the outside world. For example, every database
extension has at least a function to connect to the database, a function to send a query to the database, and
a function to close the connection to the database. Because you can have multiple database connections
open at once, the connect function gives you something by which to identify that unique connection when
you call the query and close functions: a resource (or a “handle”).
Each active resource has a unique identifier. Each identifier is a numerical index into an internal PHP lookup
table that holds information about all the active resources. PHP maintains information about each resource
in this table, including the number of references to (or uses of) the resource throughout the code. When the
last reference to a resource value goes away, the extension that created the resource is called to free any
memory, close any connection, etc., for that resource:
$res = database_connect(); // fictitious database connect function
database_query($res);
$res = "boo";
// database connection automatically closed because $res is redefined
The benefit of this automatic cleanup is best seen within functions, when the resource is assigned to a
local variable. When the function ends, the variable’s value is reclaimed by PHP:
function search() {
$res = database_connect();
database_query($res);
}
Use the is_resource() function to test whether a value is a resource:
if (is_resource($x)) {
// $x is a resource
}
27
8)NULL
There’s only one value of the NULL data type. That value is available through the case-insensitive keyword
NULL. The NULL value represents a variable that has no value (similar to Perl’s undef or Python’s None):
$aleph = "beta";
$aleph = null; // variable's value is gone
$aleph = Null; // same
Use the is_null() function to test whether a value is NULL—for instance, to see whether a variable has a
value:
if (is_null($x)) {
// $x is NULL
}
Variables
In PHP, variables are used to store and manipulate data. Variables in PHP are represented by a dollar sign ($)
followed by the variable name. They can store various types of data, including strings, numbers, arrays,
objects, and more.
$name
A variable may hold a value of any type. There is no compile-time or runtime type checking on variables. You
can replace a variable’s value with another of a different type:
$what = "Fred";
$what = 35;
There is no explicit syntax for declaring variables in PHP. The first time the value of a variable is set, the
variable is created. In other words, setting a value to a variable also functions as a declaration. For example,
this is a valid complete PHP program:
$day = 60 * 60 * 24;
echo "There are {$day} seconds in a day.\n";
There are 86400 seconds in a day.
A variable whose value has not been set behaves like the NULL value:
if ($uninitializedVariable === NULL) {
echo "Yes!";
}
Yes!
28
Variable Scope
In PHP, variable scope refers to the visibility and accessibility of variables within different parts of a script.
PHP variables can have either global scope or local scope, and the scope determines where the variable can
be accessed and modified. Understanding variable scope is crucial for writing well-organized and
maintainable code. Here's an overview of variable scope in PHP:
1. Local Scope:
- Variables declared inside a function have local scope and are only accessible within that function.
- Local variables are created when the function is called and destroyed when the function execution
completes.
- Local variables can have the same name as global variables without causing conflicts because they exist
in different scopes.
Example:
```php
$globalVar = "I am a global variable";
function myFunction() {
$localVar = "I am a local variable";
echo $localVar; // Output: I am a local variable
}
echo $globalVar; // Output: I am a global variable
echo $localVar; // This will throw an error because $localVar is not defined in the global scope
?>
globalVar is declared and initialized outside of any function, making it a global variable.It holds the value "I
am a global variable". myFunction() is defined as a function. Inside this function, we have: Declaration and
initialization of a local variable $localVar with the value "I am a local variable".
When myFunction() is called, it executes the code inside its block. The function echoes the value of the local
variable $localVar, which is "I am a local variable".After the function definition, the script echoes the value
of the global variable $globalVar. This results in the output: "I am a global variable".
Finally, the script tries to echo the value of the local variable $localVar outside the function.However, since
$localVar is defined only within the scope of the function, it is not accessible outside.This attempt to access
$localVar outside its scope causes a PHP error, typically something like "Undefined variable: localVar".
$globalVar is accessible both inside and outside the function because it's declared in the global scope. On
the other hand, $localVar is only accessible within the myFunction() function and not in the global scope,
resulting in an error when attempting to access it outside the function.
29
2.Global Scope:
- Variables declared outside of any function or class have global scope.
- Global variables can be accessed from anywhere in the script, including inside functions, classes, and
included files.
- To access a global variable from within a function, you need to use the `global` keyword or the `$GLOBALS`
array.
EXAMPLE
<?php
$globalVar = "I am a global variable";
function myFunction() {
global $globalVar;
echo $globalVar; // Output: I am a global variable
}
echo $globalVar; // Output: I am a global variable
?>
the global variable $globalVar is declared and initialized outside any function, making it accessible from both
the global scope and any functions in the script. Inside the myFunction() function, we explicitly declare
$globalVar as a global variable using the global keyword, allowing us to access its value within the function.
The script then outputs the value of $globalVar both inside and outside the function, resulting in the same
value being displayed twice.
3. Static Local Variables: PHP allows you to declare static local variables inside functions using the `static`
keyword.Static variables retain their value between function calls and are not destroyed when the function
execution completes.
<?php
function counter() {
static $count = 0;
$count++;
echo $count . "<br>";
}
counter(); // Output: 1
counter(); // Output: 2
counter(); // Output: 3
?>
30
The counter() function is defined. Inside this function A static variable $count is declared and initialized with
the value 0. Static variables retain their value between function calls.The value of $count is then incremented
by 1.The current value of $count is echoed followed by a line break (<br>).
The counter() function is called three times consecutively:
The first function call initializes the static variable $count with 0, increments it to 1, and outputs it as "1".
The second function call increments the static variable $count from 1 to 2 and outputs it as "2".
The third function call increments the static variable $count from 2 to 3 and outputs it as "3".
The counter() function demonstrates the use of a static variable ($count) to maintain state between function
calls. The static variable retains its value across multiple function invocations, allowing us to track and
increment a counter each time the function is called.
31