Chapter 2: Language Basics
Before working with larger PHP projects you need a solid understanding of the syntax and rules that form the foundation of the language. PHP code is built from statements that end with semicolons, grouped inside blocks, and organized with variables, constants, and types. This chapter explains those basics and prepares you for functions and objects in later chapters.
Syntax, Statements, and Comments
PHP scripts are composed of statements that usually end with a semicolon. Multiple statements form a block when enclosed in braces { }. Each script begins with the <?php tag and may include HTML around or between PHP blocks.
Writing statements and blocks correctly
Each statement must end with a semicolon. A block groups several statements and is often used in loops, conditionals, and functions. Whitespace and indentation make your code easier to read but do not affect execution.
<?php
$greeting = "Hello";
$name = "World";
echo $greeting . ", " . $name . "!";
?>
Adding comments for clarity
Use comments to describe intent and logic. PHP supports single-line comments with // or #, and multi-line comments between /* and */.
// This is a single-line comment
# This is another form
/*
This is a multi-line comment
that can span several lines
*/
Variables and Constants
Variables in PHP start with a dollar sign and can store any type of data. Constants hold values that do not change during execution. PHP is dynamically typed but you can still use type declarations where helpful.
Creating and using variables
Variable names begin with $ followed by a letter or underscore, and may include letters, numbers, or underscores. PHP variables are case-sensitive and assigned using =.
$language = "PHP";
$version = 8.3;
$isFun = true;
echo "I am learning $language version $version.";
Defining constants
Constants are defined with define() or the const keyword. They do not use a dollar sign and are global by default.
define("APP_NAME", "My PHP App");
const VERSION = "1.0";
echo APP_NAME;
Understanding variable scope
Variables declared inside functions are local to that function. Global variables can be accessed using the global keyword or the $GLOBALS array. Constants, by contrast, are accessible everywhere.
Scalar and Compound Types
PHP supports several scalar types (single values) and compound types (collections or objects). Understanding these helps you predict how expressions and functions behave.
Working with scalar types
Scalars include bool, int, float, and string. PHP converts between them when needed, though this can cause surprises if you are not explicit.
$count = 10; // int
$price = 19.99; // float
$title = "Book"; // string
$available = true; // bool
Exploring compound types
Compound types include array and object. Arrays hold ordered or associative collections of values, while objects group data and behavior in classes. PHP also has callable and iterable pseudo-types.
$colors = ["red", "green", "blue"];
$person = ["name" => "Robin", "role" => "Author"];
int|float).
Type Declarations and Strict Types
Modern PHP lets you declare expected types for function parameters, return values, and class properties. These declarations make code more predictable and self-documenting.
Using type declarations for safety
Type declarations enforce that only the expected types are passed to functions or methods. You can use built-in types such as int, float, string, array, and bool, or custom class names.
function add(int $a, int $b): int {
return $a + $b;
}
Enabling strict typing
By default PHP will try to convert values to match declared types. To make type checking strict, include a directive at the top of the file:
<?php
declare(strict_types=1);
With strict types enabled, passing a float to a function expecting an int will cause a TypeError.
Operators and Expressions
Operators combine values and variables into expressions. PHP supports arithmetic, assignment, comparison, logical, and string operators, among others.
Performing arithmetic and assignment
$x = 5;
$y = 2;
echo $x + $y; // 7
echo $x ** $y; // 25
Compound assignment operators such as += and *= modify variables in place.
Using comparison and logical operators
Equality == compares values after type juggling, while identity === compares both type and value. Logical operators &&, ||, and ! control conditional logic.
=== and !== to avoid unexpected conversions between strings and numbers.
Concatenating and interpolating strings
Use . to concatenate strings. When using double-quoted strings, variables are interpolated automatically.
$name = "Robin";
echo "Hello $name";
echo 'Hello ' . $name;
Include and Require
Large PHP projects use multiple files for organization. The include and require statements insert one file into another at runtime. Both evaluate the imported file in the current scope.
Including external files
Use include when the file is optional. If the file is missing, PHP issues a warning but continues execution.
include "header.php";
echo "<p>Page content</p>";
include "footer.php";
Requiring critical files
Use require for files that are essential. If the file cannot be found, PHP stops execution immediately with a fatal error.
require "config.php";
Avoiding multiple inclusions
Use include_once or require_once to ensure a file loads only once even if referenced multiple times. This prevents redeclaration errors.
require_once "init.php";
__DIR__ to build safe absolute paths.