Unit-I (PHP).docx
Unit-I (PHP).docx
1. Server-Side Scripting: PHP code is executed on the server, and only the output
(typically HTML) is sent to the user's browser.
2. Dynamic Content: PHP allows developers to generate dynamic web content based on
user input, database interactions, and more.
3. Cross-Platform: PHP runs on various platforms such as Windows, Linux, macOS, and
more, making it versatile for different environments.
4. Integration with Databases: PHP is often used in conjunction with databases,
particularly MySQL or MariaDB, to build database-driven websites.
5. Easy to Learn: PHP has a relatively simple syntax, making it a good choice for
beginners.
6. Large Community and Libraries: The PHP community is vast, and there are countless
libraries and frameworks (e.g., Laravel, Symfony, CodeIgniter) to speed up development.
1. User Request: A user requests a web page, usually by typing a URL into their browser.
2. Server-Side Processing: The web server processes the PHP file. The PHP script runs,
and any dynamic content (e.g., user input, database queries) is generated.
3. Response: After execution, the server sends the output (usually HTML) to the user’s
browser, which displays it.
A simple PHP script is embedded inside HTML using <?php and ?> tags.
<?php
echo "Hello, World!";
?>
The echo statement is used to output content to the browser. In this case, the text "Hello, World!"
will appear on the web page.
1
23UDSM401 DSC VI :PHP WITH JAVASCRIPT (UNIT-I) SEMESTER: IV
You can mix PHP code with HTML. This is often done to dynamically generate parts of a
webpage, such as displaying user information or customizing the page based on input.
<!DOCTYPE html>
<html>
<head>
<title>PHP Example</title>
</head>
<body>
<h1>Welcome to my website</h1>
<p>
<?php
echo "Today is " . date('l, F j, Y');
?>
</p>
</body>
</html>
In this example, the PHP code generates the current date and displays it inside the <p> tag.
PHP is commonly used to handle user input submitted through forms. The form can be created in
HTML, and PHP processes the data when the form is submitted.
Example: A simple form that accepts a user's name and displays a greeting:
<?php
$name = $_POST['name'];
echo "Hello, " . $name . "!";
?>
Here:
2
23UDSM401 DSC VI :PHP WITH JAVASCRIPT (UNIT-I) SEMESTER: IV
4. Connecting to a Database:
One of PHP's most powerful features is its ability to interact with databases. Most commonly,
PHP is used with MySQL or MariaDB for creating data-driven applications like blogs,
e-commerce sites, or social media platforms.
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test_db";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["name"]. " - Email: " . $row["email"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
This script connects to a MySQL database and retrieves data from a users table. The results are
displayed on the webpage.
5. PHP Frameworks:
For larger, more complex projects, PHP frameworks can help organize and speed up
development. Popular PHP frameworks include:
● Laravel: A feature-rich framework with built-in tools for routing, ORM (Eloquent),
authentication, and more.
3
23UDSM401 DSC VI :PHP WITH JAVASCRIPT (UNIT-I) SEMESTER: IV
1. Open Source: PHP is free to use, and its extensive ecosystem allows developers to build
almost anything.
2. Scalability: PHP is highly scalable, and when combined with frameworks, it can handle
projects ranging from small websites to large enterprise applications.
3. Community Support: With millions of developers worldwide, there’s a large community
to provide support, tutorials, and libraries.
4. Compatibility with Other Web Technologies: PHP works seamlessly with other web
technologies like HTML, CSS, JavaScript, and AJAX.
● Command-Line Behavior: PHP reads the contents of script.php, parses the PHP code,
and executes it.
● If there are syntax errors, PHP’s parser will return an error message, detailing the line
number and type of error.
For example:
php -l script.php
4
23UDSM401 DSC VI :PHP WITH JAVASCRIPT (UNIT-I) SEMESTER: IV
● The -l flag checks for syntax errors in a PHP file without executing it.
● If the script is syntactically correct, PHP will print No syntax errors detected in
script.php.
Example:
php
Copy code
<?php
echo "Hello, World!";
?>
Running it via the command line:
php hello.php
Outputs:
Copy code
Hello, World!
2. Using token_get_all() for Parsing PHP Code
PHP provides a built-in function called token_get_all(), which allows you to tokenize a PHP
script into a structured format that the PHP parser can use.
token_get_all():
The token_get_all() function parses PHP code and returns an array of PHP tokens. This is a great
way to analyze or inspect PHP code programmatically.
Syntax:
array token_get_all(string $source_code);
Example:
<?php
$php_code = '<?php echo "Hello, World!"; ?>';
$tokens = token_get_all($php_code);
5
23UDSM401 DSC VI :PHP WITH JAVASCRIPT (UNIT-I) SEMESTER: IV
Output:
Type: 1, Value:
Type: 4, Value: echo
Token:
Type: 3, Value: "Hello, World!"
Token: ;
In this example:
● The token_get_all() function breaks down the PHP code into smaller tokens, such as
keywords (echo), strings ("Hello, World!"), and symbols (;).
● Each token is either an array (for structured tokens) or a string (for symbols).
This allows you to examine and manipulate the structure of PHP code programmatically.
3. Using External PHP Parser Libraries (PHP-Parser)
If you're looking for a more advanced way of parsing PHP code, especially for analyzing or
manipulating it, you can use external libraries like PHP-Parser (created by Nikita Popov),
which is a widely used library for parsing PHP code into an abstract syntax tree (AST).
PHP-Parser Library:
● The PHP-Parser library transforms PHP code into an abstract syntax tree (AST),
which can then be traversed, modified, or analyzed.
● It allows you to parse PHP code into a data structure that represents the program's syntax
and logic.
Installing PHP-Parser:
composer require nikic/php-parser
Example Code:
<?php
require 'vendor/autoload.php'; // Include the Composer autoloader
use PhpParser\ParserFactory;
try {
// Parse the code
$ast = $parser->parse($code);
6
23UDSM401 DSC VI :PHP WITH JAVASCRIPT (UNIT-I) SEMESTER: IV
● The AST represents the structure of the code in a way that’s easier to manipulate
programmatically. You can analyze individual nodes, modify them, or generate new PHP
code based on the AST.
7
23UDSM401 DSC VI :PHP WITH JAVASCRIPT (UNIT-I) SEMESTER: IV
// Check for syntax errors (a more sophisticated check can be added here)
foreach ($tokens as $token) {
// Handle errors or inspect the tokens
8
23UDSM401 DSC VI :PHP WITH JAVASCRIPT (UNIT-I) SEMESTER: IV
1. Command-Line Parsing: Use the php command to run scripts and check for syntax
errors.
2. Tokenization: Use token_get_all() to break down PHP code into tokens for analysis.
3. Advanced Parsing (PHP-Parser): Use libraries like nikic/php-parser to convert PHP
code into an Abstract Syntax Tree (AST) for deeper inspection and manipulation.
4. Reflection API: Use PHP's built-in reflection capabilities to inspect classes, methods,
and properties dynamically.
Comments are an essential part of programming, as they help explain the code, provide context,
and make it easier to maintain. In PHP, comments can be added in three different ways:
single-line comments, multi-line comments, and documentation comments. Let's go through each
type and explain how and when to use them.
1. Single-Line Comments
A single-line comment is used to add brief explanations or notes on a single line. It is typically
used for short descriptions or to disable a single line of code for debugging purposes.
Syntax:
Example:
<?php
// This is a simple comment that explains the next line of code
$name = "John Doe"; // Assigning name to the variable
9
23UDSM401 DSC VI :PHP WITH JAVASCRIPT (UNIT-I) SEMESTER: IV
● Double forward slash (//): Used for comments that occupy a single line.
● Hash (#): Another way to create single-line comments (less common but still valid).
2. Multi-Line Comments
A multi-line comment is used to add explanations or notes that span multiple lines. It is useful
when you need to provide a detailed explanation or temporarily comment out large blocks of
code.
Syntax:
/*
This is a multi-line comment.
It can span across multiple lines.
Each line doesn't need a comment symbol.
*/
Example:
<?php
/*
This function takes two parameters: $a and $b.
It returns the sum of the two numbers.
*/
function add($a, $b) {
return $a + $b;
}
PHP also supports PHPDoc comments, which are a specialized form of multi-line comments
used for documenting code. These comments follow a particular structure and are commonly
used to generate documentation automatically using tools like phpDocumentor or Swagger.
PHPDoc comments start with /** and end with */. Inside, you provide metadata about the
function, class, or method, such as parameter types, return types, and descriptions.
10
23UDSM401 DSC VI :PHP WITH JAVASCRIPT (UNIT-I) SEMESTER: IV
Syntax:
/**
* This is a PHPDoc comment.
* It is typically used to describe the purpose of a function or class.
*
* @param string $name The name of the person
* @param int $age The age of the person
* @return string A greeting message
*/
Example:
<?php
/**
* This function greets the user with their name.
*
* @param string $name The name of the person to greet
* @param int $age The age of the person (optional)
* @return string The greeting message
*/
function greet($name, $age = null) {
if ($age) {
return "Hello, $name! You are $age years old.";
} else {
return "Hello, $name!";
}
}
echo greet("John", 30); // Outputs: Hello, John! You are 30 years old.
?>
In PHPDoc comments:
PHPDoc comments help developers understand the purpose of methods and functions and are
especially useful when generating documentation automatically.
● Clarity over Brevity: Comments should explain why something is done, not what is
done (unless the code is especially complex).
11
23UDSM401 DSC VI :PHP WITH JAVASCRIPT (UNIT-I) SEMESTER: IV
● Update Comments with Code: Always keep comments up-to-date with your code. If
you modify a function or class, make sure the comments are adjusted accordingly.
● Avoid Over-Commenting: Don't add comments to every line of code. The code should
be self-explanatory, and comments should only be used to clarify non-obvious sections.
● Be Descriptive with Function Comments: For functions and methods, use PHPDoc
comments to describe the parameters and return values clearly.
● Comment Out Debugging Code: Use comments to temporarily disable code (e.g.,
during testing or debugging), but avoid leaving commented-out code in production.
<?php
// Single-line comment explaining the start of the script
/*
This is a multi-line comment
explaining the purpose of the following code:
The script greets a user by their name.
*/
/**
* This function takes the name of the person and returns a greeting message.
*
* @param string $name The name of the person to greet
* @return string The greeting message
*/
function greet($name) {
// Check if the name is empty and provide an alternative greeting
if (empty($name)) {
return "Hello, Guest!";
}
return "Hello, $name!";
}
In this example:
12
23UDSM401 DSC VI :PHP WITH JAVASCRIPT (UNIT-I) SEMESTER: IV
PHP Tags
All PHP code is enclosed within <?php and ?> tags. These tags tell the PHP interpreter to
process the code inside them.
<?php
// PHP code goes here
?>
● PHP code: Written inside the <?php ... ?> tags. The code inside these tags is executed by
the server.
● HTML outside PHP tags: You can mix PHP with HTML. Any content outside the PHP
tags is considered HTML.
Example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>PHP Example</title>
</head>
<body>
<h1>Welcome to PHP!</h1>
<?php
echo "This is PHP inside an HTML page.";
?>
</body>
</html>
In this example:
In PHP, variables are essential for storing and manipulating data. Variables are used to store
values like strings, numbers, arrays, and more, which can then be processed, modified, or
displayed on web pages.
This section will cover the key concepts related to variables in PHP: how to declare them, types
of variables, naming rules, and how to use them effectively.
13
23UDSM401 DSC VI :PHP WITH JAVASCRIPT (UNIT-I) SEMESTER: IV
In PHP, a variable is declared by prefixing a name with a dollar sign ($), followed by the name
of the variable. PHP is a loosely typed language, which means you don't need to specify the type
of the variable when declaring it. The type of the variable is determined dynamically based on
the value assigned to it.
Syntax:
php
Copy code
$variable_name = value;
● $variable_name: This is the name of the variable. Variable names in PHP are
case-sensitive and must begin with a letter or an underscore (_).
● value: This is the data that the variable will hold, such as a string, integer, float, etc.
Example:
php
Copy code
<?php
$name = "Alice"; // String variable
$age = 25; // Integer variable
$height = 5.7; // Float variable
?>
● In this example:
o $name holds a string value.
o $age holds an integer value.
o $height holds a floating-point number.
php
Copy code
14
23UDSM401 DSC VI :PHP WITH JAVASCRIPT (UNIT-I) SEMESTER: IV
<?php
$name = "Alice";
$_name = "Bob";
$age1 = 30;
$userAge = 25;
?>
php
Copy code
<?php
$1age = 30; // Invalid: Starts with a number
$-age = 25; // Invalid: Starts with an invalid character
$user-age = 40; // Invalid: Contains a hyphen (-)
?>
PHP is a loosely typed language, meaning the type of a variable is determined by the value it is
assigned at runtime. Here are the main data types you can store in variables:
1. String
A string is a sequence of characters enclosed in either single (') or double (") quotes.
<?php
$message = "Hello, World!"; // Double-quoted string
$name = 'Alice'; // Single-quoted string
?>
● Single-quoted strings: Literal characters are displayed as they are, except for the escape
characters like \\, \', and \n.
● Double-quoted strings: Allow variable interpolation and escape sequences like \n for
newlines.
2. Integer
<?php
$age = 25; // Integer
$number = -100; // Negative Integer
?>
3. Float (Double)
15
23UDSM401 DSC VI :PHP WITH JAVASCRIPT (UNIT-I) SEMESTER: IV
A float (or double) is a number that contains a decimal point or is written in scientific notation.
<?php
$height = 5.8; // Float
$weight = 65.5; // Float
$temperature = 3.5e2; // Scientific notation (350)
?>
4. Boolean
<?php
$isStudent = true; // Boolean value (true)
$isAdmin = false; // Boolean value (false)
?>
5. NULL
A variable can be assigned the value NULL, which indicates that the variable has no value.
<?php
$data = NULL; // Variable is empty
?>
6. Array
<?php
// Indexed array
$fruits = array("apple", "banana", "cherry");
// Associative array
$person = array("name" => "Alice", "age" => 25);
?>
7. Object
In object-oriented programming (OOP) with PHP, an object can hold both data (properties) and
functions (methods) that operate on the data.
<?php
16
23UDSM401 DSC VI :PHP WITH JAVASCRIPT (UNIT-I) SEMESTER: IV
class Person {
public $name;
public $age;
function greet() {
return "Hello, my name is " . $this->name;
}
}
4. Variable Scope
In PHP, variables have different scopes depending on where they are declared:
1. Global Scope
Variables declared outside any function or class have global scope and are accessible from
anywhere in the script.
<?php
$name = "John"; // Global variable
function greet() {
global $name; // Accessing global variable inside the function
echo "Hello, $name";
}
2. Local Scope
Variables declared inside a function or method have local scope and are accessible only within
that function.
<?php
function sayHi() {
$name = "Alice"; // Local variable
17
23UDSM401 DSC VI :PHP WITH JAVASCRIPT (UNIT-I) SEMESTER: IV
3. Global Keyword
To access a global variable inside a function, you need to use the global keyword.
<?php
$age = 30; // Global variable
function displayAge() {
global $age; // Access the global variable
echo "Age is $age"; // Outputs: Age is 30
}
displayAge();
?>
4. Superglobals
PHP provides special built-in global arrays called superglobals that are always accessible from
anywhere in the script. Some common superglobals are:
<?php
// URL: example.com?name=Alice
echo $_GET['name']; // Outputs: Alice
?>
5. Variable Variables
PHP allows the use of variable variables, where the name of the variable can be dynamically
set.
<?php
18
23UDSM401 DSC VI :PHP WITH JAVASCRIPT (UNIT-I) SEMESTER: IV
$varName = "hello";
$$varName = "world"; // This creates a variable $hello with the value "world"
In this example:
6. Unsetting Variables
<?php
$name = "Alice";
unset($name); // Removes the variable $name
PHP Operators
Operators are used in PHP to perform operations on variables and values. PHP operators can be
categorized into several types based on their functionalities.
1. Arithmetic Operators
Types:
● + (Addition)
● - (Subtraction)
● * (Multiplication)
● / (Division)
● % (Modulus/ Remainder)
● ++ (Increment)
● -- (Decrement)
Syntax:
19
23UDSM401 DSC VI :PHP WITH JAVASCRIPT (UNIT-I) SEMESTER: IV
Example:
$a = 10;
$b = 5;
echo $a + $b; // Output: 15
echo $a - $b; // Output: 5
echo $a * $b; // Output: 50
echo $a / $b; // Output: 2
echo $a % $b; // Output: 0
$a++;
echo $a; // Output: 11
Output:
15
5
50
2
0
11
Advantages:
Disadvantages:
2. Assignment Operators
Types:
● = (Simple Assignment)
● += (Add and assign)
● -= (Subtract and assign)
20
23UDSM401 DSC VI :PHP WITH JAVASCRIPT (UNIT-I) SEMESTER: IV
Syntax:
$variable = $value;
$variable += $value;
$variable -= $value;
$variable *= $value;
$variable /= $value;
$variable %= $value;
Example:
$a = 10;
$a += 5; // $a = 10 + 5 = 15
$a -= 3; // $a = 15 - 3 = 12
$a *= 2; // $a = 12 * 2 = 24
$a /= 4; // $a = 24 / 4 = 6
$a %= 3; // $a = 6 % 3 = 0
echo $a; // Output: 0
Output:
Advantages:
Disadvantages:
3. Comparison Operators
Types:
● == (Equal to)
21
23UDSM401 DSC VI :PHP WITH JAVASCRIPT (UNIT-I) SEMESTER: IV
Syntax:
$a == $b; // Equal to
$a === $b; // Identical to
$a != $b; // Not equal to
$a !== $b; // Not identical to
$a > $b; // Greater than
$a < $b; // Less than
$a >= $b; // Greater than or equal to
$a <= $b; // Less than or equal to
Example:
$a = 5;
$b = 10;
var_dump($a == $b); // Output: bool(false)
var_dump($a != $b); // Output: bool(true)
var_dump($a > $b); // Output: bool(false)
var_dump($a <= $b); // Output: bool(true)
Output:
bool(false)
bool(true)
bool(false)
bool(true)
Advantages:
Disadvantages:
● Can be tricky when comparing data types (e.g., loose comparison == vs. strict
comparison ===).
● Can lead to unexpected results when types differ (e.g., 0 == '0' is true).
22
23UDSM401 DSC VI :PHP WITH JAVASCRIPT (UNIT-I) SEMESTER: IV
4. Logical Operators
Logical operators are used to perform logical operations, often in conditional statements.
Types:
Syntax:
Example:
$a = true;
$b = false;
var_dump($a && $b); // Output: bool(false)
var_dump($a || $b); // Output: bool(true)
var_dump(!$a); // Output: bool(false)
Output:
bool(false)
bool(true)
bool(false)
Advantages:
Disadvantages:
5. String Operators
Types:
23
23UDSM401 DSC VI :PHP WITH JAVASCRIPT (UNIT-I) SEMESTER: IV
● . (Concatenation)
● .= (Concatenation assignment)
Syntax:
Example:
$a = "Hello";
$b = "World";
echo $a . " " . $b; // Output: Hello World
$a .= $b; // $a = "HelloWorld"
echo $a; // Output: HelloWorld
Output:
Hello World
HelloWorld
Advantages:
Disadvantages:
6. Increment/Decrement Operators
Increment and decrement operators are used to increase or decrease a variable's value by 1.
Types:
● ++ (Increment)
● -- (Decrement)
Syntax:
$a++; // Post-increment
++$a; // Pre-increment
$a--; // Post-decrement
--$a; // Pre-decrement
24
23UDSM401 DSC VI :PHP WITH JAVASCRIPT (UNIT-I) SEMESTER: IV
Example:
$a = 5;
echo $a++; // Output: 5 (post-increment, $a is now 6)
echo ++$a; // Output: 7 (pre-increment)
Output:
5
7
Advantages:
Disadvantages:
7. Array Operators
Types:
● + (Union)
● == (Equality)
● === (Identity)
Syntax:
Example:
25
23UDSM401 DSC VI :PHP WITH JAVASCRIPT (UNIT-I) SEMESTER: IV
Output:
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
[5] => 6
)
bool(true)
Advantages:
Disadvantages:
● The union operator (+) does not handle duplicate keys well.
● Array comparisons using == and === can be tricky due to order and reference issues.
Syntax:
@expression;
Example:
Advantages:
● Helps in situations where you want to suppress certain errors without affecting the rest of
the code.
Disadvantages:
26
23UDSM401 DSC VI :PHP WITH JAVASCRIPT (UNIT-I) SEMESTER: IV
● Using the error control operator can hide important errors and lead to difficult-to-debug
issues.
● Should be used sparingly.
Type casting operators are used to convert one data type to another.
Types:
Syntax:
(int)$var;
(bool)$var;
(float)$var;
(string)$var;
Example:
$var = "123.45";
echo (int)$var; // Output: 123
echo (bool)$var; // Output: 1
Output:
123
1
Advantages:
Disadvantages:
1. Functionality
27
23UDSM401 DSC VI :PHP WITH JAVASCRIPT (UNIT-I) SEMESTER: IV
● echo:
o echo is not a function; it's a language construct.
o It can accept one or more arguments, meaning you can pass multiple strings or
variables to it without needing parentheses.
o Example:
● print:
o print is a function, and it always returns a value.
o It can only take one argument at a time, so you can only print a single string or
variable per call.
o Example:
o Return value: print returns 1 after it has printed the output. This can be used in
expressions (though it's not common).
if (print("Hello World!")) {
// Do something
}
2. Return Values
● echo:
o Does not return any value. It just outputs the data.
● print:
o Returns 1, which means it can be used in expressions or as part of conditional
statements. This is a very minor difference, but it could have practical
applications in more complex situations.
3. Performance
● echo is slightly faster than print because it doesn't return a value, and it can take multiple
arguments. This makes echo a bit more efficient for outputting multiple pieces of data at
once.
● print, while not significantly slower, involves a function call and always returns a value,
making it marginally less efficient for simple output tasks.
4. Use Cases
28
23UDSM401 DSC VI :PHP WITH JAVASCRIPT (UNIT-I) SEMESTER: IV
● echo:
o Preferred for general output purposes, especially when you have multiple strings
or variables to output. It’s also slightly more performant for simple output.
● print:
o Can be used when you need a return value or want to output something with the
added functionality of returning 1 (though this is rare in practice).
5. Syntax
● echo:
o Can take multiple arguments:
echo("Hello World!");
● print:
o Can only take one argument, and parentheses are not optional:
print("Hello World!");
Variable scope
In PHP, variable scope refers to the context in which a variable is accessible or visible. It
determines where and how a variable can be used in a script. PHP variables have different types
of scopes, and understanding them is essential for writing clean, efficient, and bug-free code.
1. Global Scope
2. Local Scope
3. Function/Method Scope
4. Static Scope
5. Superglobals
1. Global Scope
Variables declared outside of any function or class are considered global variables. They are
accessible from anywhere in the script, but not inside functions or methods unless explicitly
brought into the function scope.
29
23UDSM401 DSC VI :PHP WITH JAVASCRIPT (UNIT-I) SEMESTER: IV
Example:
function testGlobalScope() {
// Trying to access $globalVar here will give an error
echo $globalVar; // This will result in an error.
}
testGlobalScope();
function testGlobal() {
global $globalVar; // Accessing global variable
echo $globalVar; // Outputs: I am a global variable.
}
testGlobal();
function testGlobal() {
echo $GLOBALS['globalVar']; // Outputs: I am a global variable.
}
testGlobal();
2. Local Scope
A local variable is defined inside a function or method and can only be accessed within that
function. Once the function execution ends, the local variable is destroyed.
● Example:
function testLocalScope() {
$localVar = "I am a local variable.";
echo $localVar; // Outputs: I am a local variable.
}
30
23UDSM401 DSC VI :PHP WITH JAVASCRIPT (UNIT-I) SEMESTER: IV
testLocalScope();
3. Function/Method Scope
A variable declared within a function or method is local to that function and cannot be accessed
outside it. The variable exists only while the function is running.
● Example:
function exampleFunction() {
$functionVar = "This is a function-scoped variable.";
echo $functionVar; // Outputs: This is a function-scoped variable.
}
exampleFunction();
4. Static Scope
A static variable inside a function retains its value between function calls. Normally, local
variables are destroyed when the function finishes executing, but a static variable persists across
multiple calls to the function.
● Example:
function countCalls() {
static $counter = 0;
$counter++;
echo $counter; // Outputs the number of times the function is called.
}
countCalls(); // Outputs: 1
countCalls(); // Outputs: 2
countCalls(); // Outputs: 3
In the above example, the $counter variable retains its value between function calls because it's
declared as static.
5. Superglobals
31
23UDSM401 DSC VI :PHP WITH JAVASCRIPT (UNIT-I) SEMESTER: IV
PHP provides superglobals — built-in global variables that are always accessible, regardless of
scope. These variables are predefined by PHP and can be accessed from anywhere in the script
(even inside functions and classes) without needing to use the global keyword.
// URL: example.php?name=John&age=25
When variables are passed to functions, they are passed by value by default. This means that a
copy of the variable is passed into the function, and changes made inside the function do not
affect the original variable. However, you can pass variables by reference if you want changes
inside the function to affect the original variable.
● Passing by Value:
function modifyValue($var) {
$var = $var + 10;
}
$num = 5;
modifyValue($num);
echo $num; // Outputs: 5 (the original value is not modified)
● Passing by Reference: To pass by reference, you use the & operator before the variable
in the function definition.
function modifyValueByReference(&$var) {
$var = $var + 10;
}
32
23UDSM401 DSC VI :PHP WITH JAVASCRIPT (UNIT-I) SEMESTER: IV
$num = 5;
modifyValueByReference($num);
echo $num; // Outputs: 15 (the original value is modified)
Expressions
In PHP, expressions are combinations of values, variables, operators, and functions that are
evaluated to produce a result. An expression can be as simple as a single value or as complex as
a series of operations that combine values and variables.
1. Simple Expressions
2. Arithmetic Expressions
3. String Expressions
4. Logical Expressions
5. Comparison Expressions
6. Assignment Expressions
7. Array Expressions
8. Function Calls as Expressions
1. Simple Expressions
A simple expression is just a single value or variable, which can be evaluated directly.
Example:
In this example, the expression $number = 42 assigns the value 42 to the variable $number.
2. Arithmetic Expressions
Example:
$a = 5;
$b = 10;
33
23UDSM401 DSC VI :PHP WITH JAVASCRIPT (UNIT-I) SEMESTER: IV
3. String Expressions
String expressions involve the concatenation or manipulation of strings using operators like .
(concatenation) or .=, and can include string interpolation.
● String Concatenation:
$firstName = "John";
$lastName = "Doe";
$fullName = $firstName . " " . $lastName; // Concatenation (John Doe)
● String Interpolation:
$firstName = "John";
$lastName = "Doe";
$fullName = "$firstName $lastName"; // John Doe (using interpolation)
$greeting = "Hello";
$greeting .= " World!"; // Now $greeting contains "Hello World!"
4. Logical Expressions
Logical expressions evaluate boolean values and involve logical operators such as && (AND), ||
(OR), ! (NOT), xor (exclusive OR).
Example:
$a = true;
$b = false;
5. Comparison Expressions
34
23UDSM401 DSC VI :PHP WITH JAVASCRIPT (UNIT-I) SEMESTER: IV
Comparison expressions are used to compare two values and return a boolean result (true or
false). They involve operators like ==, ===, !=, !==, >, <, >=, and <=.
Example:
$a = 10;
$b = 20;
6. Assignment Expressions
Assignment expressions are used to assign a value to a variable. The most common operator for
assignment is =, but there are also shorthand operators for compound assignments such as +=, -=,
*=, /=, and .=.
Example:
$a = 5; // Simple assignment
$a += 10; // $a = $a + 10 (Compound addition)
$a -= 3; // $a = $a - 3 (Compound subtraction)
$a *= 2; // $a = $a * 2 (Compound multiplication)
$a /= 5; // $a = $a / 5 (Compound division)
$a .= " is cool!"; // Concatenate string to $a
7. Array Expressions
An array expression is used to create or manipulate arrays. Arrays are a special type of
expression in PHP and can be defined using array() (in older versions) or the shorthand [] syntax
(since PHP 5.4).
Example:
// Associative array
$person = [
35
23UDSM401 DSC VI :PHP WITH JAVASCRIPT (UNIT-I) SEMESTER: IV
// Array manipulation
$numbers[] = 5; // Add 5 to the array (push operation)
array_push($numbers, 6); // Another way to add 6 to the array
Function calls in PHP are also expressions. When you call a function, the result (return value) of
that function is treated as an expression that can be used in further operations.
Example:
Literals Variable
1. Literals in PHP
A literal is a fixed value that is written directly into the code. Literals represent constant data
values and are not variables. They can be numbers, strings, or other types of fixed values. When
PHP encounters a literal in the code, it treats it as an immediate value.
1. Integer Literals
Integer literals are used to represent whole numbers. They can be written in decimal,
hexadecimal, octal, or binary formats.
Examples:
36
23UDSM401 DSC VI :PHP WITH JAVASCRIPT (UNIT-I) SEMESTER: IV
Examples:
3. String Literals
String literals represent a sequence of characters. They can be enclosed in either single
quotes (') or double quotes ("), and the difference lies in how they handle special
characters and variables.
o Single-quoted string:
Single quotes preserve the exact characters inside and do not parse variables or
escape sequences (except \\ and \').
o Double-quoted string:
Double quotes can parse escape sequences (like \n, \t, etc.) and variables inside
the string.
$name = "John";
$double_quoted = "Hello, $name!"; // Double-quoted string with variable
interpolation
$escaped_string = "This is a line\nwith a newline."; // String with escape
sequence
4. Boolean Literals
Boolean literals represent the two possible boolean values: true and false.
Examples:
5. Null Literal
The null literal represents a variable with no value assigned. It's used to indicate that a
variable has no value or is not set.
Example:
37
23UDSM401 DSC VI :PHP WITH JAVASCRIPT (UNIT-I) SEMESTER: IV
6. Array Literals
Arrays can be defined directly in PHP using the array() construct (or shorthand [] in PHP
5.4+).
Examples:
2. Variables in PHP
A variable is a container that holds a value, which can be changed during the execution of the
program. In PHP, variables start with a dollar sign ($), followed by the variable name. The value
of a variable can be a literal or the result of an expression.
1. Variable Declaration
Variables are automatically declared when they are first assigned a value. PHP does not
require explicit type declaration, meaning a variable can hold any type of data.
Example:
Example:
$userName = "Alice";
$user_age = 30;
$_variable = "value"; // Valid
$2ndVariable = "Invalid"; // Invalid: cannot start with a number
38
23UDSM401 DSC VI :PHP WITH JAVASCRIPT (UNIT-I) SEMESTER: IV
Example:
4. Variable Scope
Variables in PHP have a scope, which determines where they can be accessed. The
common scopes in PHP are local, global, and static.
o Local Variables are accessible only within the function or block in which they
are declared.
o Global Variables are accessible from anywhere in the script (using global
keyword or $GLOBALS array).
o Static Variables retain their value across function calls.
5. Variable Interpolation in Strings
In PHP, you can embed variables inside strings, but the behavior differs between single
and double-quoted strings.
o Single quotes do not parse variables:
$name = 'John';
echo 'Hello, $name'; // Outputs: Hello, $name
$name = 'John';
echo "Hello, $name"; // Outputs: Hello, John
● Literals are fixed values that appear directly in the code and cannot be changed.
39
23UDSM401 DSC VI :PHP WITH JAVASCRIPT (UNIT-I) SEMESTER: IV
● Variables store data that can change during the execution of a program.
● Strings can be declared with single quotes (') or double quotes ("), and the behavior of
variable interpolation differs between the two.
● PHP variables are loosely typed, meaning the type of a variable is determined by the
value it holds at runtime.
Operator precedence refers to the order in which operators are evaluated in an expression. In
PHP, some operators have higher precedence than others, meaning they are evaluated first.
Understanding operator precedence is important for writing correct expressions and avoiding
logical errors.
Operator Precedence
PHP uses a well-defined order of precedence when evaluating expressions. Operators with
higher precedence are evaluated before operators with lower precedence.
2. Unary Operators
$a = 5;
echo ++$a; // Pre-increment: Outputs 6
40
23UDSM401 DSC VI :PHP WITH JAVASCRIPT (UNIT-I) SEMESTER: IV
3. Multiplicative Operators
● Multiplication (*)
● Division (/)
● Modulo (%): Returns the remainder of a division.
$x = 10;
$y = 3;
echo $x * $y; // Outputs: 30
echo $x % $y; // Outputs: 1 (remainder of division)
4. Additive Operators
● Addition (+)
● Subtraction (-)
$a = 10;
$b = 5;
echo $a + $b; // Outputs: 15
echo $a - $b; // Outputs: 5
5. Shift Operators
● Left Shift (<<): Shifts bits to the left (multiplies by powers of 2).
● Right Shift (>>): Shifts bits to the right (divides by powers of 2).
$a = 5; // 101 in binary
echo $a << 1; // Left shift: Outputs 10 (1010 in binary)
echo $a >> 1; // Right shift: Outputs 2 (10 in binary)
6. Relational Operators
● Equal (==)
● Identical (===): Checks both value and type.
● Not equal (!=)
● Not identical (!==)
41
23UDSM401 DSC VI :PHP WITH JAVASCRIPT (UNIT-I) SEMESTER: IV
$a = 10;
$b = 5;
echo $a == $b; // Outputs: false (10 is not equal to 5)
echo $a > $b; // Outputs: true (10 is greater than 5)
7. Bitwise Operators
● AND (&)
● OR (|)
● XOR (^)
● AND assignment (&=)
● OR assignment (|=)
● XOR assignment (^=)
● Shift left (<<)
● Shift right (>>)
$a = 5; // 0101 in binary
$b = 3; // 0011 in binary
echo $a & $b; // AND operation: Outputs 1 (0001 in binary)
8. Logical Operators
$a = true;
$b = false;
echo $a && $b; // Outputs: false (both operands must be true for AND)
echo $a || $b; // Outputs: true (one operand is true for OR)
9. Assignment Operators
42
23UDSM401 DSC VI :PHP WITH JAVASCRIPT (UNIT-I) SEMESTER: IV
$a = 10;
$a += 5; // $a = $a + 5 (Result: $a is 15)
$a *= 2; // $a = $a * 2 (Result: $a is 30)
● Ternary (? :)
$age = 20;
$status = ($age >= 18) ? 'Adult' : 'Minor'; // If $age >= 18, status is 'Adult', otherwise 'Minor'
echo $status; // Outputs: Adult
The null coalescing operator (??) is used to check if a variable is set and is not null. If it is set,
the operator returns its value; otherwise, it returns a default value.
$username = null;
$defaultUsername = "Guest";
echo $username ?? $defaultUsername; // Outputs: Guest (since $username is null)
The comma operator (,) is used to separate multiple expressions in a single statement. All
expressions are evaluated, but only the last one is returned.
$a = 10;
$b = 20;
echo ($a++, $b++); // Outputs: 20 (Only $b is returned, both $a and $b are incremented)
43
23UDSM401 DSC VI :PHP WITH JAVASCRIPT (UNIT-I) SEMESTER: IV
Associativity
Associativity refers to the direction in which operators are evaluated when they have the same
precedence in an expression. While precedence determines the order in which operators are
applied, associativity defines whether operators are evaluated from left to right (left-associative)
or from right to left (right-associative) when they share the same precedence.
Types of Associativity
In PHP, most operators are left-associative, meaning they are evaluated from left to right.
However, some operators are right-associative, meaning they are evaluated from right to left.
1. Left-Associative Operators
Left-associative operators are evaluated from left to right. This means that when multiple
operators of the same precedence appear in an expression, PHP evaluates them starting from the
leftmost one.
● Arithmetic operators: +, -, *, /, %
● Relational operators: ==, !=, >, <, >=, <=
● Logical operators: &&, ||
● Bitwise operators: &, |, ^, <<, >>
● Assignment operators: =, +=, -=, *=, /=, etc.
44
23UDSM401 DSC VI :PHP WITH JAVASCRIPT (UNIT-I) SEMESTER: IV
Example:
$a = 5;
$b = 10;
$c = 15;
In the above example, since the operators + and - have the same precedence and are
left-associative, PHP evaluates them from left to right.
2. Right-Associative Operators
Right-associative operators are evaluated from right to left. This means that when multiple
operators of the same precedence appear in an expression, PHP evaluates them starting from the
rightmost one.
Example:
$a = 5;
$b = 10;
$c = 2;
Here, the assignment operator (=) is right-associative, so PHP first assigns $c to $b, and then
assigns the result to $a. The final result of $a is 2, since the value of $c is 2.
$a = 10;
$b = 5;
$result = $a > $b ? 1 : 0 ? 2 : 3; // Right-to-left evaluation
echo $result; // Outputs: 2 (Evaluated as: ($a > $b ? 1 : 0) ? 2 : 3)
In this case, the ternary operator (?:) is right-associative, so PHP first evaluates the second
ternary operation (0 ? 2 : 3), which results in 3, and then evaluates the first ternary ($a > $b ? 1 :
3), which results in 2.
45
23UDSM401 DSC VI :PHP WITH JAVASCRIPT (UNIT-I) SEMESTER: IV
Here's a table summarizing the operators, their precedence, and associativity in PHP:
$a = 5;
$b = 10;
$c = 15;
$a = 5;
$b = 10;
$c = 15;
In the second example, the assignment operator (=) is right-associative, so PHP evaluates $b =
$c first, then $a = $b.
1. Left-associative operators: These operators are evaluated from left to right. Most
operators, such as arithmetic, logical, and relational operators, are left-associative in PHP.
2. Right-associative operators: These operators are evaluated from right to left. Notable
examples include the assignment operator (=), the ternary operator (?:), and the
exponentiation operator (**) in PHP 5.6+.
3. Operator precedence determines which operators are evaluated first, and associativity
determines the direction of evaluation when multiple operators with the same precedence
appear in an expression.
4. Parentheses (()) can always be used to override both precedence and associativity,
ensuring a specific order of evaluation.
Relational Operators
Relational operators in PHP are used to compare two values. They return a boolean value: true
if the comparison is true, and false if the comparison is false.
These operators are essential for making decisions in PHP programs, such as checking if two
variables are equal, greater, or less than each other.
47
23UDSM401 DSC VI :PHP WITH JAVASCRIPT (UNIT-I) SEMESTER: IV
1. Equal to (==)
The == operator checks if two values are equal, but it does not consider their data types.
$a = 5;
$b = '5';
var_dump($a == $b); // true: because the values are equal (ignoring type)
2. Identical (===)
The === operator checks if two values are equal and of the same type.
$a = 5;
$b = '5';
The != operator checks if two values are not equal, but it does not consider their types.
$a = 5;
$b = 10;
The !== operator checks if two values are not equal or if their types are different.
48
23UDSM401 DSC VI :PHP WITH JAVASCRIPT (UNIT-I) SEMESTER: IV
$a = 5;
$b = '5';
The > operator checks if the left operand is greater than the right operand.
$a = 10;
$b = 5;
The < operator checks if the left operand is less than the right operand.
$a = 3;
$b = 5;
The >= operator checks if the left operand is greater than or equal to the right operand.
$a = 10;
$b = 10;
The <= operator checks if the left operand is less than or equal to the right operand.
$a = 5;
$b = 8;
PHP performs type juggling when using relational operators if the operands are of different
types. This means PHP will attempt to convert the values to comparable types.
49
23UDSM401 DSC VI :PHP WITH JAVASCRIPT (UNIT-I) SEMESTER: IV
For example:
$a = "5"; // String
$b = 5; // Integer
However, with the === operator, PHP will not perform type conversion:
Example:
Example:
var_dump('0' === 0); // false: string '0' is not the same type as integer 0
Example:
var_dump(0 != '0'); // false: values are considered equal after type conversion
var_dump(0 !== '0'); // true: different types (integer vs string)
Summary
● Equality:
o ==: Checks if the values are equal, regardless of type.
o ===: Checks if the values are equal and of the same type.
● Inequality:
o !=: Checks if the values are not equal, regardless of type.
o !==: Checks if the values are not equal or not of the same type.
● Comparison:
50
23UDSM401 DSC VI :PHP WITH JAVASCRIPT (UNIT-I) SEMESTER: IV
o >: Checks if the left operand is greater than the right operand.
o <: Checks if the left operand is less than the right operand.
o >=: Checks if the left operand is greater than or equal to the right operand.
o <=: Checks if the left operand is less than or equal to the right operand.
Conditionals
Definition:
Conditionals are programming constructs used to perform different actions based on whether a
specific condition is true or false. They help control the flow of the program.
Types:
● if
● else
● elseif
● switch
● Ternary Operator (?)
Syntax Overview:
Definition:
Syntax:
if (condition) {
// Code to be executed if the condition is true
}
Program:
$age = 18;
if ($age >= 18) {
51
23UDSM401 DSC VI :PHP WITH JAVASCRIPT (UNIT-I) SEMESTER: IV
Output:
Result:
The condition $age >= 18 is true, so the block inside the if statement is executed.
Advantages:
Disadvantages:
● Doesn't provide alternatives for false conditions unless paired with else or elseif.
● Can become cumbersome with multiple conditions.
Definition:
The else statement allows you to execute a block of code when the if condition is false.
Syntax:
if (condition) {
// Code to be executed if the condition is true
} else {
// Code to be executed if the condition is false
}
Program:
$age = 15;
if ($age >= 18) {
echo "You are an adult.";
} else {
echo "You are a minor.";
}
Output:
52
23UDSM401 DSC VI :PHP WITH JAVASCRIPT (UNIT-I) SEMESTER: IV
Result:
Since the condition $age >= 18 is false, the code inside the else block is executed.
Advantages:
Disadvantages:
Definition:
The elseif statement allows you to check additional conditions if the initial if condition is false.
Syntax:
if (condition1) {
// Code if condition1 is true
} elseif (condition2) {
// Code if condition2 is true
} else {
// Code if no conditions are true
}
Program:
$age = 20;
if ($age < 13) {
echo "You are a child.";
} elseif ($age < 18) {
echo "You are a teenager.";
} else {
echo "You are an adult.";
}
Output:
53
23UDSM401 DSC VI :PHP WITH JAVASCRIPT (UNIT-I) SEMESTER: IV
Result:
Since the first condition $age < 13 is false and the second $age < 18 is also false, the code in the
else block is executed.
Advantages:
Disadvantages:
Definition:
The switch statement is used when you have multiple conditions that you want to test against a
single value. It is often cleaner and more efficient than multiple if-elseif conditions.
Syntax:
switch (expression) {
case value1:
// Code to be executed if expression equals value1
break;
case value2:
// Code to be executed if expression equals value2
break;
default:
// Code to be executed if no cases match
}
Program:
$day = 3;
switch ($day) {
case 1:
echo "Monday";
break;
case 2:
echo "Tuesday";
break;
54
23UDSM401 DSC VI :PHP WITH JAVASCRIPT (UNIT-I) SEMESTER: IV
case 3:
echo "Wednesday";
break;
case 4:
echo "Thursday";
break;
case 5:
echo "Friday";
break;
case 6:
echo "Saturday";
break;
case 7:
echo "Sunday";
break;
default:
echo "Invalid day";
}
Output:
Wednesday
Result:
Since $day is 3, the case case 3 is executed, and the output is "Wednesday".
Advantages:
● Clean and efficient for checking a single value against multiple conditions.
● Easier to read than long if-elseif chains.
Disadvantages:
Definition:
The ternary operator is a shorthand for the if-else statement. It is used to assign a value based on
a condition in one line.
Syntax:
55
23UDSM401 DSC VI :PHP WITH JAVASCRIPT (UNIT-I) SEMESTER: IV
Program:
$age = 20;
$status = ($age >= 18) ? "Adult" : "Minor";
echo $status;
Output:
Adult
Result:
The condition $age >= 18 is true, so the value "Adult" is assigned to $status, and "Adult" is
printed.
Advantages:
Disadvantages:
Summary
Looping
56
23UDSM401 DSC VI :PHP WITH JAVASCRIPT (UNIT-I) SEMESTER: IV
Definition:
Looping in PHP allows you to repeatedly execute a block of code as long as a specified
condition is true. Loops are essential for performing repetitive tasks and can make the code more
efficient by reducing redundancy.
Types of Loops:
● while Loop
● do...while Loop
● for Loop
● foreach Loop (iterates over arrays, discussed separately)
● break Statement (used to exit a loop)
● continue Statement (used to skip one iteration of a loop)
Definition:
The while loop is used to execute a block of code as long as a specified condition is true. If the
condition is false initially, the loop will not run.
Syntax:
while (condition) {
// Code to be executed
}
Program Example:
$count = 1;
while ($count <= 5) {
echo "Count: $count<br>";
$count++;
}
Output:
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5
Result:
57
23UDSM401 DSC VI :PHP WITH JAVASCRIPT (UNIT-I) SEMESTER: IV
The loop runs five times because $count starts at 1 and is incremented until it reaches 5. When
$count becomes 6, the condition ($count <= 5) becomes false, and the loop terminates.
Advantages:
Disadvantages:
● If the condition is not met or is incorrectly written, it could lead to an infinite loop (unless
a proper exit condition is given).
● The loop may not execute at all if the condition is false initially.
Definition:
The do...while loop executes the block of code at least once, even if the condition is false,
because the condition is checked after the code block is executed.
Syntax:
do {
// Code to be executed
} while (condition);
Program Example:
$count = 1;
do {
echo "Count: $count<br>";
$count++;
} while ($count <= 5);
Output:
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5
Result:
58
23UDSM401 DSC VI :PHP WITH JAVASCRIPT (UNIT-I) SEMESTER: IV
The loop runs five times, just like the while loop, but it guarantees that the code inside the loop
runs at least once, even if the condition is false initially.
Advantages:
● Ensures that the block of code is executed at least once, which is useful in some cases
where the initial condition might not be true.
● Suitable when you want the loop to execute before checking the condition.
Disadvantages:
● If the loop condition is false after the first iteration, it may not be ideal in some cases as it
may lead to unnecessary computation.
● The loop could run indefinitely if the condition is not properly managed.
Definition:
The for loop is generally used when the number of iterations is known before entering the loop.
It has three parts: initialization, condition, and increment (or decrement).
Syntax:
Program Example:
Output:
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5
Result:
59
23UDSM401 DSC VI :PHP WITH JAVASCRIPT (UNIT-I) SEMESTER: IV
The loop executes five times. The initialization $count = 1 starts the loop, the condition $count
<= 5 ensures it continues until $count becomes 6, and $count++ increments the counter after
each iteration.
Advantages:
Disadvantages:
● Less flexible than while or do...while if the number of iterations is not known upfront.
● Requires three parts to be specified, which can be cumbersome for some situations.
Definition:
The break statement is used to exit from a loop prematurely, regardless of the loop's condition. It
terminates the loop and passes control to the next statement after the loop.
Syntax:
break;
Program Example:
Output:
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5
Result:
60
23UDSM401 DSC VI :PHP WITH JAVASCRIPT (UNIT-I) SEMESTER: IV
The loop terminates when $count reaches 6, due to the break statement. As a result, it does not
print numbers greater than 5.
Advantages:
Disadvantages:
Definition:
The continue statement is used to skip the current iteration of a loop and continue with the next
iteration. It only affects the current iteration, not the entire loop.
Syntax:
continue;
Program Example:
Output:
Count: 1
Count: 2
Count: 4
Count: 5
Result:
The loop prints numbers 1, 2, 4, and 5. When $count is 3, the continue statement is executed,
which skips that iteration.
61
23UDSM401 DSC VI :PHP WITH JAVASCRIPT (UNIT-I) SEMESTER: IV
Advantages:
● Helps to skip over specific iterations without breaking out of the loop entirely.
● Can be useful in filtering or skipping unnecessary iterations based on a condition.
Disadvantages:
When is the
Loop Condition
Condition Loop Execution Typical Use Case
Type Check
Checked?
Use when you don't know
If condition is false
Before the Checked before how many times the loop
while initially, the loop doesn't
loop each iteration will run but need to check
run.
the condition first.
Always runs at least once,
After the Checked after Use when you need to ensure
do...while even if the condition is
loop each iteration the code runs at least once.
false initially.
Runs a known number of
Use when you know how
Before the Checked before times based on the
for many times the loop should
loop each iteration initialization and
run.
increment.
Definition
● Implicit Casting (Type Juggling): In PHP, implicit casting happens automatically when
the PHP engine converts one data type to another. This happens when you use variables
in an expression where PHP requires a certain type. PHP does this automatically without
any intervention by the developer.
● Explicit Casting: Explicit casting occurs when the developer manually converts one data
type to another. This is done using type-casting syntax or functions.
Syntax
1. Implicit Casting:
o Implicit casting is automatic. You don't need to use any special syntax for this.
o Example: $sum = $intVar + $floatVar; — Here, PHP automatically converts
$intVar to a float before performing the addition.
2. Explicit Casting:
62
23UDSM401 DSC VI :PHP WITH JAVASCRIPT (UNIT-I) SEMESTER: IV
o Using settype() function: This function changes the type of the variable directly.
<?php
$integer = 7; // Integer
$float = 3.14; // Float
$sum = $integer + $float; // Implicit casting occurs here
Output
Sum: 10.14
Explanation
● The integer $integer is automatically cast to a float because $float is of type float, and the
addition requires both operands to be of the same type.
● PHP implicitly converts $integer to a float before performing the addition.
<?php
$number = "123.45"; // String
$intNumber = (int)$number; // Explicitly cast string to integer
Output
63
23UDSM401 DSC VI :PHP WITH JAVASCRIPT (UNIT-I) SEMESTER: IV
Explanation
● The string "123.45" is explicitly cast to an integer using (int) syntax. The decimal part is
truncated, and only the integer part is retained.
● The output shows 123, the result of the explicit cast.
Advantages
● Implicit Casting:
o Convenience: You don't need to worry about type conversion when performing
operations; PHP handles it for you.
o Less Code: Since it happens automatically, you don't need to write extra code for
type conversion.
● Explicit Casting:
o Control: You have full control over how and when type conversion happens.
o Clarity: Makes the code clearer when you need specific type conversion,
reducing potential errors due to unexpected automatic type changes.
o Performance: Explicit casting can sometimes improve performance because it
removes ambiguity, making the type conversion explicit.
Disadvantages
● Implicit Casting:
o Unpredictability: It might lead to unexpected behavior or bugs, especially if PHP
performs conversions that the developer didn’t intend.
o Harder to Debug: Implicit conversions may not be immediately obvious, making
the code harder to understand and debug.
● Explicit Casting:
o Verbose: You need to write extra code to ensure variables are cast properly.
o Performance: In some cases, explicit casting might slightly decrease
performance, especially if done repeatedly in a large loop or complex operation.
Definition
In PHP, dynamic linking refers to the ability to load extensions or shared libraries dynamically
at runtime. This enables PHP to use additional features provided by these extensions without
needing to recompile or restart the server. Dynamic linking is often used to add functionalities
like database connectivity, encryption, and more.
64
23UDSM401 DSC VI :PHP WITH JAVASCRIPT (UNIT-I) SEMESTER: IV
Syntax
1. Using extension_loaded():
o To check whether a specific extension is loaded at runtime.
if (extension_loaded('json')) {
echo 'JSON extension is available!';
} else {
echo 'JSON extension is not available.';
}
3. In php.ini:
o Extensions can be loaded automatically by specifying them in the php.ini
configuration file.
<?php
if (extension_loaded('json')) {
echo 'JSON extension is available!';
} else {
echo 'JSON extension is not available.';
}
?>
Output
Explanation
● This program checks if the json extension is available and loaded in the current PHP
environment.
● If the extension is loaded, it outputs "JSON extension is available!", otherwise, it says
"not available".
65
23UDSM401 DSC VI :PHP WITH JAVASCRIPT (UNIT-I) SEMESTER: IV
Advantages
1. Flexibility:
o Extensions can be loaded at runtime, which means you can add or remove
features without needing to restart the web server or recompile PHP.
2. Modular Approach:
o Extensions allow you to add only the required functionalities, keeping PHP
lightweight. You can load only the extensions you need for a specific application.
3. Performance:
o Loading only the necessary extensions can improve the performance and reduce
the memory footprint.
4. No Need for Recompilation:
o You don't need to recompile the PHP interpreter to add or remove features; just
load/unload extensions dynamically.
Disadvantages
66