2. PHP Syntax and Variables
2. PHP Syntax and Variables
Outline
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 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.
<?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.
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!";
?>
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.).
• 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.
<?php
$name = "Alice"; // String variable
$age = 25; // Integer variable
$is_student = true; // Boolean variable
?>
• 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.
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.
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.
<?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
?>
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.
<?php
$globalMessage = "I am a global variable."; // Global variable
function displayGlobalVariable() {
global $globalMessage; // Declare the global variable inside the
function
echo $globalMessage;
}
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.
<?php
function countCalls() {
static $counter = 0; // Static variable initialized only once
$counter++; // Increment the counter
echo "Function called $counter times.<br>";
}
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.
<?php
function greetUser($name) { // $name is a function parameter
echo "Hello, $name!";
}
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
Example
<?php
$greeting = "Hello, PHP!";
echo $greeting;
?>
2. Integer
Example
<?php
$year = 2023;
?>
BASICS OF PHP SOMATECH IT
3. Float (or Double)
Example
<?php
$price = 19.99;
?>
4. Boolean
Example
<?php
$is_active = true;
?>
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?
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"
?>
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.
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
// 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. 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.