0% found this document useful (0 votes)
10 views8 pages

2. PHP Syntax and Variables

Uploaded by

imsisia
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
10 views8 pages

2. PHP Syntax and Variables

Uploaded by

imsisia
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 8

BASIC PHP TRAINING NOTES

Outline

− PHP syntax overview


− Declaring and using variables
− Data types (string, integer, float, Boolean, etc.)
− Constants in PHP

PHP Syntax and Variables

PHP is known for its simple syntax and ability to embed directly within HTML, which makes it a
popular language for web development. Let’s explore the core elements of PHP syntax, variables,
data types, and constants, and see examples to understand each concept in practice.

PHP Syntax Overview

PHP Tag Structure

• PHP code is embedded within HTML using <?php ... ?> tags. Anything written within
these tags is processed by the server.
• PHP statements end with a semicolon (;), signaling the end of each command.

Example of PHP Syntax

<?php
echo "Welcome to our PHP Session!";
?>

• Explanation The echo statement outputs text to the browser, in this case displaying
Welcome to our PHP Session!.

Comments in PHP

Comments are used to annotate code, providing explanations or notes for developers.

• Single-line comment: Starts with //


• Multi-line comment: Enclosed between /* ... */

Example of Comments

<?php
// This is a single-line comment
BASICS OF PHP SOMATECH IT
echo "Hello, World!";

/* This is a
multi-line comment */
echo "PHP is fun!";
?>

Declaring and Using PHP Variables

What is a Variable?

• A variable is a symbolic name that holds data. In PHP, variables start with a $ symbol
and store different types of data (numbers, text, etc.).

Declaring Variables in PHP

• To declare a variable, start with the $ symbol, followed by the variable name (using only
letters, numbers, and underscores).
• PHP is a loosely typed language, meaning you don’t need to declare the data type. PHP
automatically determines it based on the assigned value.

Example of Variable Declaration

<?php
$name = "Alice"; // String variable
$age = 25; // Integer variable
$is_student = true; // Boolean variable
?>

Real-World Application of Variables

• Variables are crucial in web development. For example, in an e-commerce site, you
might store product prices, user IDs, and names in variables, allowing you to manage and
display data dynamically.

PHP Variable Types

In PHP, variables play an essential role in storing and manipulating data throughout a script.
Understanding variable scope—the context where a variable is accessible—is crucial for writing
efficient, organized code. Let’s look at the main types of variables in PHP local, global, static,
and function parameters.

BASICS OF PHP SOMATECH IT


1. Local Variables

Definition
Local variables are declared and used within a specific function or block of code. They are not
accessible outside of that function. Local variables are created when the function runs and are
destroyed after the function completes.

Example of a Local Variable

<?php
function showLocalVariable() {
$message = "This is a local variable."; // Local variable
echo $message;
}
showLocalVariable(); // Outputs "This is a local variable."
// echo $message; // This would cause an error since $message is not
accessible here
?>

Real-World Application of Local Variables


Local variables are helpful in cases where you need temporary data, like a calculation inside a
function. They avoid conflicts by keeping data encapsulated within specific code blocks.

2. Global Variables

Definition
Global variables are declared outside of any function and are accessible throughout the script. To
access a global variable within a function, you must explicitly declare it as global using the global
keyword.

Example of a Global Variable

<?php
$globalMessage = "I am a global variable."; // Global variable

function displayGlobalVariable() {
global $globalMessage; // Declare the global variable inside the
function
echo $globalMessage;
}

displayGlobalVariable(); // Outputs "I am a global variable."


?>

Real-World Application of Global Variables


Global variables are useful for data that needs to be shared across multiple functions, like
configuration settings (e.g., database credentials) or tracking information (e.g., user session data).
BASICS OF PHP SOMATECH IT
Note
Excessive use of global variables can make debugging challenging and increase the likelihood of
errors due to accidental data changes. Limit their use to necessary scenarios.

3. Static Variables

Definition
Static variables maintain their value even after the function that declares them has finished
executing. When the function is called again, the static variable will hold its previous value.

Example of a Static Variable

<?php
function countCalls() {
static $counter = 0; // Static variable initialized only once
$counter++; // Increment the counter
echo "Function called $counter times.<br>";
}

countCalls(); // Outputs "Function called 1 times."


countCalls(); // Outputs "Function called 2 times."
countCalls(); // Outputs "Function called 3 times."
?>

Real-World Application of Static Variables


Static variables help count how many times a function is called, storing the result of a complex
computation, or caching values within functions.

4. Function Parameters

Definition
Function parameters are variables passed to a function when it is called. They allow you to send
data into functions for processing. Function parameters act like local variables within the
function and are destroyed when the function completes.

Example of Function Parameters

<?php
function greetUser($name) { // $name is a function parameter
echo "Hello, $name!";
}

greetUser("Alice"); // Outputs "Hello, Alice!"


greetUser("Bob"); // Outputs "Hello, Bob!"
?>
BASICS OF PHP SOMATECH IT
Real-World Application of Function Parameters
Function parameters are essential in writing reusable functions. For example, if you have a
function that calculates the area of a rectangle, you can pass the length and width as parameters,
making the function versatile.

Summary

• Local Variables Exist only within functions or code blocks, ideal for temporary data or
function-specific logic.
• Global Variables Accessible across the entire script; use with caution as they can be
modified from anywhere in the script.
• Static Variables Retain their value between function calls, useful for counters or caching
within a function.
• Function Parameters Allow values to be passed into a function, making it flexible and
reusable.

Understanding these variable types and their scopes helps keep your code organized, enhances
security, and improves the performance of your PHP applications.

Data Types

PHP automatically identifies the data type of a variable based on the value assigned to it. Here
are the primary data types in PHP

1. String

• A sequence of characters, typically text.


• Strings are enclosed in single (') or double (") quotes.

Example

<?php
$greeting = "Hello, PHP!";
echo $greeting;
?>

2. Integer

• A whole number, positive or negative, without decimals.

Example

<?php
$year = 2023;
?>
BASICS OF PHP SOMATECH IT
3. Float (or Double)

• A number with a decimal point.

Example

<?php
$price = 19.99;
?>

4. Boolean

• Represents a true or false value.


• Often used in control structures like if statements.

Example

<?php
$is_active = true;
?>

Real-World Application of Data Types

Data types help store different types of information. For example, a user’s age could be
stored as an integer, while their name would be a string and a product price as a float.

Constants in PHP

What is a Constant?

• A constant is a fixed value that, once defined, cannot be changed or undefined.


• Constants are useful for values that remain the same throughout a script, like a tax rate,
company name, or website URL.

Declaring a Constant

• Use the define() function to declare a constant. By convention, constant names are
uppercase.
• Constants do not use the $ symbol.

Syntax

define("CONSTANT_NAME", value);

Example

<?php
BASICS OF PHP SOMATECH IT
define("SITE_NAME", "MyWebsite");
echo SITE_NAME; // Outputs "MyWebsite"
?>

Real-World Application of Constants

Constants are essential for values that do not change, such as tax rates in a financial
application or a site’s name on each page.

Full Example Using Syntax, Variables, Data Types, and Constants

Let’s put it all together in a script that calculates the total cost after tax for a product

<?php
// Define a constant for tax rate
define("TAX_RATE", 0.08);

// Variables
$product_name = "Laptop";
$base_price = 1200.00; // Float for product price
$quantity = 2; // Integer for quantity

// Calculate total cost before and after tax


$total_cost = $base_price * $quantity;
$total_cost_with_tax = $total_cost * (1 + TAX_RATE);

// Display results
echo "Product $product_name<br>";
echo "Base Price $$base_price<br>";
echo "Quantity $quantity<br>";
echo "Total Cost (without tax) $$total_cost<br>";
echo "Total Cost (with tax) $$total_cost_with_tax";
?>

Explanation

1. We define a constant TAX_RATE to represent the tax percentage.


2. Variables store information on the product name, base price, and quantity.
3. The total cost is calculated, both without tax and with tax.
4. The result is displayed, showing how constants, variables, and basic calculations come
together in PHP.

BASICS OF PHP SOMATECH IT


Self-Assessment

1. What is a static variable in PHP, and how does it differ from a local variable? Give a brief
example.
2. Explain the difference between a local and a global variable in PHP. When would it be better
to use each type, and what potential issues could arise from using too many global variables?
3. Imagine you are building an e-commerce site where each user visit counts toward the total
page views. Write a PHP function that uses a static variable to track and display how many
times the function has been called. Explain why a static variable is useful in this case.
4. You are developing a PHP application that needs to access the same database credentials from
multiple functions. Declare a global variable for the database credentials and write two
functions—one that connects to the database and another that fetches user information—
showing how the global variable is used across both functions.
5. Write a PHP script with a function parameter that takes a user’s name as input and returns a
customized greeting message. Then, call this function with at least three different names and
display the results. Explain the importance of using function parameters in this scenario.

BASICS OF PHP SOMATECH IT

You might also like