0% found this document useful (0 votes)
21 views22 pages

PHP Basics: Variables, Functions, and OOP

The document provides a comprehensive introduction to PHP, covering its basic concepts, syntax, and features, including variable declaration, data types, and operators. It also discusses control flow, functions, object-oriented programming, file handling, and database interaction using SQL. Additionally, it outlines how to create PHP scripts and manipulate data effectively.

Uploaded by

sakthi98076
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views22 pages

PHP Basics: Variables, Functions, and OOP

The document provides a comprehensive introduction to PHP, covering its basic concepts, syntax, and features, including variable declaration, data types, and operators. It also discusses control flow, functions, object-oriented programming, file handling, and database interaction using SQL. Additionally, it outlines how to create PHP scripts and manipulate data effectively.

Uploaded by

sakthi98076
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

320C5C/Web Technology

UNIT I
Introducing PHP – Basic development Concepts – Creating first
PHP Scripts – Using Variable and Operators – Storing Data in
variable – Understanding Data types – Setting and Checking
variables Data types – Using Constants – Manipulating Variables
with Operators.
UNIT II
Controlling Program Flow: Writing Simple Conditional
Statements - Writing More Complex Conditional Statements –
Repeating Action with Loops – Working with String and Numeric
Functions.
UNIT IV
Using Functions and Classes: Creating User-Defined Functions -
Creating Classes – Using Advanced OOP Concepts. Working with
Files and Directories: Reading Files Writing Files Processing
Directories.
UNIT V
Working with Database and SQL : Introducing Database and
SQL- Using MySQL Adding and modifying Data-Handling Errors
– Using SQLite Extension and PDO Extension. Introduction XML
- Simple XML and DOM Extension.
UNIT I
Introducing PHP – Basic development Concepts – Creating first
PHP Scripts – Using Variable and Operators – Storing Data in
variable – Understanding Data types – Setting and Checking
variables Data types – Using Constants – Manipulating Variables
with Operators.

Introducing PHP
What is PHP ?
PHP stands for Hypertext Pre-processor.
PHP is a server-side scripting language that is used to develop
Static websites or Dynamic websites or Web applications.
PHP is an open-source, interpreted, and object-oriented scripting
language that can be executed at the server-side.
• It’s embedded within HTML and is executed on the server.
• PHP files have a .php extension and can contain text, HTML,
CSS, JavaScript, and PHP code.

What Can PHP Do?


• PHP can generate dynamic page content
• PHP can create, open, read, write, delete, and close files on the
server
• PHP can collect form data
• PHP can send and receive cookies
• PHP can add, delete, modify data in your database
• PHP can be used to control user-access
• PHP can encrypt data

List the PHP Features and Explain


vi. Server-Side Scripting: PHP runs on the server and generates dynamic
content (HTML, JSON, XML) that is sent to the user's browser.
vii. Flexibility: PHP scripts can run on any device- mobile, tablet, or PC.
viii. Efficient: PHP is a versatile, reliable, and efficient programming
language. The memory management of PHP is very efficient.
ix. Security: PHP has many pre-defined functions for data encryption.
x. Objective oriented: PHP supports object-oriented programming
features like data encapsulation, inheritance, abstraction, polymorphism,
etc.
xi. Error Handling: PHP provides built-in functions for error detection and
handling
xii. Database Integration: PHP works with many databases like MySQL,
PostgreSQL, SQLite, Oracle, MongoDB, etc
xiii. Extensive Libraries: PHP supports many built-in functions and third-
party libraries
xiv. Session and Cookie Handling: PHP can store and manage user
sessions and cookies easily
xv: Cross Web Server: It supports many web servers like IIS, Apache,
Tomcat, etc

Basic development Concepts


Write the syntax of PHP script.
PHP Syntax
A PHP script can be placed anywhere in the document.
A PHP script starts with <?php and ends with ?>

<?php
// PHP code goes here
?>
Example:
<?php
echo "Hello, PHP!";
?>

Output
Hello, PHP!

How PHP Works?


Below are the following steps, which show how PHP works:
Step 1: User Requests the Page
Step 2: Web Server Receives the Request
Step 3: PHP Processes the Request
Step 4: Database Interaction
Step 5: PHP Responds with Dynamic Content
Step 6: Web Browser Receives the Response
Explain about Creating first PHP Scripts
Creating a first PHP script involves a few fundamental steps:
Steps
1 Install XAMPP or WAMP
2 Create a .php file
3 Write PHP code using <?php ... ?>
4 Save the file in the server directory
5 Access it through [Link]

Step 1: Set Up Your Environment


Before writing PHP code, we need a server environment because PHP is a
server-side language.
• XAMPP – Cross-platform Apache, MySQL, PHP, and Perl
• WAMP – Windows-based
Step 2: Create a PHP File
1. Open a code editor (like VS Code, Sublime, Notepad++)
2. Create a new file and save it as: [Link]
Step 3: Write Your First PHP Code
Inside [Link], write:
<?php
echo "Hello, World!";
?>
• <?php ... ?> is the PHP opening and closing tag.
• echo is a PHP statement used to output text to the browser.

Step 4: Save Your File in the Server Directory

• If we are using XAMPP, save your file in:


C:\xampp\htdocs\[Link]

Step 5: Run Your Script


1. Start Apache from the XAMPP Control Panel.
2. Open a browser and go to: [Link]
3. we should see:
4. Hello, World!

Variable and Operators in PHP

Define Variable in PHP


A variable is a named location in memory to store data temporarily.
PHP is dynamically typed language,
PHP automatically determines the type of a variable based on the value
assigned to it
e.g. $var1 = 10; // integer
we need not have to write string $name or int $age.
PHP figures out the data type for each variable automatically based on
the assigned value.

How to Declare Variables in PHP?


Syntax:
$variableName = value;
Rules:
• Must start with a $
• Must begin with a letter or underscore (_), not a number
• Case-sensitive ($Name and $name are different)
• Use = to assign a value.
• End the line with a semicolon (;)
• No type declaration

<?php
$name = "Alice"; // String
$age = 25; // Integer
$price = 10.99; // Float
$isStudent = true; // Boolean
?>
Explain Output in PHP
Output in PHP means displaying data (text, variables, HTML, etc.) to the
web browser.
PHP provides two primary ways to display output:

1. echo Outputs one or more strings


2. print Outputs a string (returns 1)

1. Using echo
• The most commonly used output function.
• Can output strings, variables, HTML, numbers, etc.
• Faster than print and can take multiple parameters.
Syntax:
echo "Hello, world!";
2. Using print
• Works like echo, but returns 1, so it can be used in expressions.
• Slightly slower than echo

Syntax:

print "This is a test.";

Setting and Checking variables Data types

Explain about Setting Variables and Data Types in PHP in


detail
[Link]() Function

The isset() function is used to check if a variable is set and is not


null.

Syntax of isset()
isset(var1, var2, ...)
Here, var1, var2, etc., represent the variables we want to check

Example:

<?php

$var = "Hello, World!";

if (isset($var)) {

echo "The variable is set.";

?>

Output
The variable is set

2. Checking Variable Data Types

i) gettype()

The gettype() function returns the type of a variable.

Syntax
gettype(variable);

PHP provides several functions to check the data type of a variable

gettype($variable): Returns the type of the variable as a string


(e.g., "string",)

ii) var_dump() in PHP


In PHP, the var_dump() function is one function that displays
information about a variable or arrays. The information displayed
includes the type of the variable and its value. It’s especially
useful for debugging.

Syntax:
void var_dump($value_1, ...$value_n);

<?php

$age = 30;
$name = "Alice";
$pi = 3.14;
$isAdmin = true;

var_dump($age);
var_dump($name);
var_dump($pi);
var_dump($isAdmin);
?>

Output:
int(30)
string(5) "Alice"
float(3.14)
bool(true)

iii) is_type() Functions:


PHP provides a set of is_type() functions to check for
specific data types:
Type Checking Functions

Type Checking Functions:


• is_array(): Checks if a variable is an array.
• is_bool(): Checks if a variable is a boolean.
• is_float() (or is_double()): Checks if a variable is a
float (double).
• is_int() (or is_integer()): Checks if a variable is an
integer.
• is_null(): Checks if a variable is NULL.
• is_numeric(): Checks if a variable contains a numeric
value (integer, float, or a numeric string).
• is_object(): Checks if a variable is an object.
• is_resource(): Checks if a variable is a resource (e.g.,
a file handle, database connection).
• is_string(): Checks if a variable is a string.

Define Constants
A constant is a name or identifier used to store a fixed value
that does not change during the execution of a PHP script.

PHP constants can be defined by 2 ways:


1. Using define() function
2. Using const keyword

[Link] define() function


To create a constant the define() function is used

Syntax: define(name, value, case-insensitive)

name: Specifies the name of the constant


value: Specifies the value of the constant
case-insensitive: Specifies whether the constant name should
be case-insensitive. Default is false

e.g.
define("GREETING", "Welcome to [Link]!");
echo GREETING;

OUTPUT:

Welcome to [Link]!

Here constant PI is case-insensitive.


2. const Keyword
We can also create a constant by using the const keyword.

Example:
<?php
const MYCAR = "Volvo";

echo MYCAR;
?>

Output:

Volvo

Manipulating Variables with Operators.

What is Operators in PHP and explain its types?


Definition:
Operators in PHP are symbols used to perform operations on
variables and values.
There are several operators supported by PHP which are
categorized into following categories:
1. Arithmetic operators
2. Assignment operators
3. Comparison operators
4. Increment/Decrement operators
5. Logical operators
6. String operators
7. Array operators

1. Arithmetic Operators
PHP arithmetic operators are used to perform operations like
addition, subtraction, multiplication etc.
Below is a list of arithmetic operators:
Example
<?php
$x=8;
$y=4;
echo ($x + $y); // outputs 12
echo ($x - $y); // outputs 4
echo ($x * $y); // outputs 32
echo ($x / $y); // outputs 2
echo ($x % $y); // outputs 2
?>
2. Assignment Operators
PHP assignment operators are used to assign values to variables

<?php
$a = 5; // Assign 5 to $a
$a += 3; // $a = $a + 3 (now $a is 8)
$a -= 2; // $a = $a - 2 (now $a is 6)
$a *= 2; // $a = $a * 2 (now $a is 12)
$a /= 3; // $a = $a / 3 (now $a is 4)
$a %= 2; // $a = $a % 2 (now $a is 0)
?>
3. Comparison Operators
PHP comparison operators are Used in conditions (e.g., if
statements) to compare values

Operator Meaning Example Description


== Equal $x == $y Returns true
if x and Y are
equal
=== Identical (same type) $x === $y Returns true
if x and Y are
equal and of
same type
!= Not equal $x != $y Returns true
if x and Y are
not equal
!== Not identical $x !== $y Returns true
if x and Y are
not equal and
of same type
> Greater than $x > $y Returns true
if X is greater
than Y
< Less than $x < $y Returns true
if X is less
than Y
>= Greater or equal $x >= $y Returns true
if X is greater
than or equal
to Y
<= Less or equal $x <= $y Returns true
if X is less
than or equal
to Y
<> Not equal $x <>$y Returns true
if X and Y are
not equal
Example
<? php
$a = 5;
$b = "5";
var_dump($a == $b); // true (equal, type not checked)
var_dump($a === $b); // false (equal and same type)
var_dump($a != $b); // false (not equal)
var_dump($a !== $b); // true (not equal or not same type)
var_dump($a > 3); // true
var_dump($a < 10); // true
var_dump($a >= 5); // true
var_dump($a <= 4); // false
?>

4. Increment/Decrement Operators
The increment/decrement operators are used to increment the
value of variable by 1 or decrement the value of variable by 1.
The increment operator is ++ and decrement operator is –-.

Operator Name Example

++$x Pre-increment Increases before use

$x++ Post-increment Increases after use

--$x Pre-decrement Decreases before use

$x-- Post-decrement Decreases after use

Example:
<?php
$a = 5;
echo $a++; // 5 (Post-increment: return, then increment)
echo $a; // 6
echo ++$a; // 7 (Pre-increment: increment, then return)
echo $a--; // 7
echo $a; // 6
?>
5. Logical Operators
PHP logical operators are Used to combine multiple conditional
statements.
The logical operators are
• && or and (Logical AND)
• || or or (Logical OR)
• ! (Logical NOT)
• xor (Logical XOR)

Example:
<?php
$a = true;
$b = false;
var_dump($a && $b); // false (AND)
var_dump($a || $b); // true (OR)
var_dump(!$a); // false (NOT)
?>
[Link] operators
PHP provides two String operators Used to join (concatenate)
strings

<?php
$a = "Hello";
$b = " World";
echo $a . $b; // Hello World (concatenation)
$a .= $b; // $a = $a . $b
echo $a; // Hello World?>

[Link] operators
Array operators in PHP are used to compare or combine
arrays.
List of Array Operators in PHP

Storing Data in variable


How to Store Data in Variables
In PHP, variables are used to store data such as numbers,
strings, arrays, objects, etc.,
Syntax:
$variableName = value;
• The variable name starts with $.
• The = operator assigns the value on the right to the variable
on the left.
• The value can be a string, number, boolean, array, or other
data types.
e.g. $name = "Alice"; // String data
PHP Data Types
Data Types define the type of data a variable can store.
The data type is used to specify which kind of data the
variable can hold.
However, PHP is a loosely typed language so there is no
need to specify the datatype while declaring the variables.

Scalar Data Types


Scalar data types are those data types in PHP which are used to
represent a single value.
There are four kinds of scalar data types available in PHP, which
are as follows:
1. String
2. Integer
3. Float
4. Boolean
[Link]
A string is a sequence of characters enclosed by single quotes (‘)
or double quotes (“).
For example:
<?php
$name = "Hello";
echo $name; // Output: Hello
?>
Output
Hello

2. Integer
An integer is a whole number (positive or negative) without
decimals.
For example:
<?php
$age = 25;
echo $age; // Output: 25
?>
Output
25
[Link]
A float is a number with a decimal point
<?php
$price = 99.99;
echo $price; // Output: 99.99
?>
Output
99.99
[Link]
A boolean represents either true or false.
<?php
$isActive = true;
if ($isActive) {
echo "Active";
}
?>
Output
Active

Compound Data Types


Compound data types in PHP are used to store more than one
value of the same type.
PHP supports two types of compound data types. They are as
follows:
1. Array
2. Object

[Link]
An array is a variable that can hold more than one value at a
time.
<?php
$colors = ["red", "green", "blue"];
echo $colors[1]; // Output: green
?>
Output
green

2. Object
An object is a compound data type in PHP that stores both data
and functions.
It is an instance of a class, which acts as a template for creating
objects.
Objects are explicitly declared and created from the new
keyword.
<?php
class Car {
public $brand = "Toyota";
}
$car = new Car();
echo $car->brand; // Output: Toyota
?>
Output
Toyota

Special Data Types

There are two types of special data types in PHP. They are as
follows:
1. NULL
2. Resource
1. NULL
A NULL value means the variable has no value.

Example: $var = NULL;

2. Resource

A special resource type is not an actual data type in PHP.


Actually, it is a special variable which stores the reference to
access an external resource such as a PHP file.

e.g. $handle = fopen("[Link]", "r");

PHP Comments:
A comment in PHP code is a line that is not read or executed as
part of the program
• Comments are usually written within the block of PHP code to
explain the functionality of the code.
• It will helps to understand the code and used for future
reference.
Comments are not displayed in the output, they are ignored by
the PHP engine.
Types:
• single line Comments # or //
• multi line comments /* ........... */

EXAMPLE OF COMMENT IN PHP


<?php
// This is a single-line comment

# This is also a single-line comment

/* This is a
multi-line comment */
?>

Explain Embedding PHP within HTML with an example

Embedding PHP within HTML


we can embed php file anywhere in our html program.
Inside a PHP file we can write HTML and inside html program
you can write php code.
<!DOCTYPE html>
<html>
<body>

<h1>My first PHP page</h1>


<?php
echo "Hello World!";
?>

</body>
</html>

Output:

My first PHP page


Hello World!

You might also like