Site Logo
Find Your Local Branch

Software Development

Learn | PHP Course: Beginner to Intermediate

Home

What it is: This is the starting place for the course. You learn what PHP does and how we will practice.

Why it is used (real-life example): Websites use PHP to show pages that change for each user, like a welcome message after you log in.

Step-by-step
  • Think of PHP as code that runs on the server (not in the browser).
  • The server runs PHP and sends back HTML to the browser.
  • In this course, you will write small PHP files and read their output.
Code example 1: First output
<?php>
echo "Hello from PHP!";
?>

This code uses echo to send text to the browser.

Code example 2: Mixing PHP and HTML
<h1>My Page</h1>
<?php>
echo "<p>This paragraph was created by PHP.</p>";
?>

The browser receives normal HTML, even though PHP built part of it.

Common mistakes
  • Forgetting the semicolon at the end of a PHP statement.
  • Writing PHP code outside <?php> tags.
  • Expecting PHP to run directly in the browser (it must run on a server).
Tips / best practices
  • Keep one small goal per file while learning.
  • Read errors carefully; they often point to the exact line.
  • Use clear text output first, then build HTML later.

Introduction

What it is: PHP is a server-side programming language used to build dynamic web pages.

Why it is used (real-life example): An online store can use PHP to show your cart items and calculate the total price for you.

Step-by-step
  • A browser sends a request to a server (like asking for index.php).
  • The server runs the PHP code.
  • PHP can read data (like URL parameters or form data).
  • PHP creates a response (often HTML) and sends it back.
Code example 1: Showing the current date
<?php>
echo date("Y-m-d");
?>

date("Y-m-d") creates a text date like 2026-03-23.

Code example 2: Reading a URL value
<?php>
$name = "Guest";
if (isset($_GET["name"])) {
  $name = $_GET["name"];
}
echo "Hello, " . $name;
?>

Step explanation: $_GET holds values from the URL. isset checks if a key exists. Then we print a greeting.

Common mistakes
  • Using $_GET without checking isset first.
  • Trusting user input without validation (users can send anything).
  • Forgetting that PHP runs on the server, so browser console will not show PHP errors.
Tips / best practices
  • Always treat user input as unsafe until you validate it.
  • Start by printing simple outputs to understand the request/response flow.
  • Use meaningful variable names like $name and $total.

Syntax

What it is: Syntax is the set of rules for writing valid PHP code, like where to put semicolons, braces, and variables.

Why it is used (real-life example): When you write correct syntax, your login page or contact form works without breaking.

Step-by-step
  • PHP code usually starts with <?php.
  • Statements end with a semicolon ;.
  • Variables start with $ (example: $age).
  • Use braces { } for code blocks, like inside if.
Code example 1: Variables and echo
<?php>
$firstName = "Ada";
$age = 20;
echo $firstName;
echo " is " . $age . " years old.";
?>

Step explanation: We store values in variables, then use . to join text together.

Code example 2: If statement
<?php>
$score = 75;
if ($score >= 50) {
  echo "Pass";
} else {
  echo "Fail";
}
?>

The condition $score >= 50 decides which block runs.

Common mistakes
  • Missing a semicolon after a statement like echo.
  • Using = (assignment) when you meant == (comparison).
  • Forgetting to close braces } in an if block.
Tips / best practices
  • Use consistent indentation so blocks are easy to read.
  • Prefer strict comparisons when possible, like ===.
  • Keep lines short and readable while learning.

Variables

What it is: A variable is a named place to store a value, like a number or text.

Why it is used (real-life example): If you store a user name in a variable, you can show it in many places without rewriting the text each time.

Step-by-step
  • In PHP, a variable starts with $.
  • Use = to put a value into it.
  • Use echo to print the variable.
Code example 1
<?php>
$name = "Mina";
echo $name;
?>

This creates a variable named $name and prints its value.

Code example 2
<?php>
$price = 10;
$qty = 3;
$total = $price * $qty;
echo $total;
?>

Here we store numbers and calculate a new value in $total.

Common mistakes
  • Forgetting the $ at the start of the variable name.
  • Using spaces in a variable name, like $user name (not allowed).
  • Using = when you meant comparison (later you will use ==).
Tips / best practices
  • Use clear names like $firstName or $totalPrice.
  • Keep variables small and focused: one meaning per variable.
  • Initialize variables before using them.

Data Types

What it is: A data type is the kind of value you store, like text, number, or true/false.

Why it is used (real-life example): A product price should be a number, but a product name should be text. Using the right type helps avoid wrong results.

Step-by-step
  • Common types: string (text), int (whole number), float (decimal), bool (true/false), array (list).
  • PHP can guess the type, but you should understand what you are storing.
  • Use var_dump() to see the value and its type.
Code example 1
<?php>
$title = "Book";
$pages = 120;
var_dump($title);
var_dump($pages);
?>

var_dump shows that $title is a string and $pages is an integer.

Code example 2
<?php>
$isMember = true;
$rating = 4.5;
var_dump($isMember);
var_dump($rating);
?>

This stores a boolean and a float (decimal number).

Common mistakes
  • Mixing numbers and text by accident, like "10" + 5 and expecting text output.
  • Assuming "false" is the same as false (it is not).
  • Forgetting that decimals like 4.5 are not integers.
Tips / best practices
  • Use var_dump() while learning to understand what PHP is doing.
  • Keep data types consistent (prices always numbers, names always strings).
  • Convert types on purpose when needed (do not rely on guessing).

Operators

What it is: Operators are symbols that do work with values, like adding numbers or joining text.

Why it is used (real-life example): You can calculate a cart total with math operators, and build a greeting message with text operators.

Step-by-step
  • Math operators: +, -, *, /.
  • String join operator in PHP is . (dot).
  • Assignment operator = stores a value in a variable.
Code example 1
<?php>
$subtotal = 50;
$tax = 5;
$total = $subtotal + $tax;
echo $total;
?>

We add two numbers to get a final total.

Code example 2
<?php>
$first = "Hello";
$user = "Sam";
$message = $first . ", " . $user;
echo $message;
?>

We join strings using the dot operator to create one message.

Common mistakes
  • Using + to join strings (in PHP you should use .).
  • Forgetting parentheses when needed, which can change the result.
  • Confusing = (assign) with == (compare).
Tips / best practices
  • Use parentheses to make math clear, like ($a + $b) * $c.
  • Build strings in small parts, then join them.
  • Name variables clearly so your operations read like a story.

Strings

What it is: A string is text, like a name, an email, or a message.

Why it is used: In real life, you show text to users. Example: “Welcome, Sara”.

Step-by-step
  • Create a string using quotes.
  • Join (combine) strings using the dot . operator.
  • Use built-in functions like strlen and strtolower to work with text.
Code example 1: joining text
<?php>
$firstName = "Sara";
$message = "Welcome, " . $firstName . "!";
echo $message; // Welcome, Sara!
?>

Here, . joins pieces of text into one message.

Code example 2: useful string functions
<?php>
$email = "[email protected]";
echo strlen($email); // length of the text
echo "<br>";
echo strtolower($email); // [email protected]
?>

This shows how to get the text length and how to make text lowercase.

Common mistakes
  • Using + to join strings (PHP uses .).
  • Forgetting quotes around text.
  • Mixing single quotes and variables: in single quotes, variables are not replaced.
Tips / best practices
  • Use double quotes when you want variables inside the text.
  • Use trim() to remove extra spaces from user input.
  • Keep user text safe when printing in HTML (escape it later when you learn output safety).

Arrays

What it is: An array is a list that holds many values in one variable.

Why it is used: In real life, you may have a list of product names or a list of user IDs.

Step-by-step
  • Create an array with [].
  • Read a value using an index like [0].
  • Add new values with [] = ....
  • Loop through values using foreach.
Code example 1: indexed array
<?php>
$colors = ["red", "green", "blue"];
echo $colors[0]; // red
echo "<br>";
$colors[] = "yellow";
echo $colors[3]; // yellow
?>

Index 0 is the first item. Adding with [] puts the item at the end.

Code example 2: looping with foreach
<?php>
$tasks = ["Wash car", "Buy milk", "Study PHP"];
foreach ($tasks as $task) {
echo "Task: " . $task . "<br>";
}
?>

The loop takes each item and prints it, one by one.

Common mistakes
  • Using an index that does not exist (it can cause warnings or unexpected results).
  • Forgetting that arrays start at index 0.
  • Mixing up arrays and strings (a string is not a list).
Tips / best practices
  • Use count() to know how many items you have.
  • Use foreach for simple loops (it is easy to read).
  • Keep arrays focused: one array for one kind of data (like only names).

Conditionals

What it is: Conditionals let your code make decisions using if, else, and elseif.

Why it is used: In real life, you show different messages. Example: if a user is logged in, show “Dashboard”, else show “Login”.

Step-by-step
  • Start with an if and a condition that returns true/false.
  • Run one block when it is true.
  • Use else for the false case.
  • Use elseif to check another condition.
Code example 1: simple if/else
<?php>
$isLoggedIn = false;
if ($isLoggedIn) {
echo "Welcome back!";
} else {
echo "Please log in.";
}
?>

If $isLoggedIn is true, the first message shows. If not, the second message shows.

Code example 2: elseif for multiple choices
<?php>
$score = 72;
if ($score >= 90) {
echo "Grade: A";
} elseif ($score >= 70) {
echo "Grade: B";
} else {
echo "Grade: C";
}
?>

PHP checks conditions from top to bottom and stops at the first true one.

Common mistakes
  • Using = instead of == (assignment vs comparison).
  • Forgetting braces { } and getting confusing results.
  • Writing conditions that are hard to read (too many checks at once).
Tips / best practices
  • Keep each condition small and clear.
  • Use strict comparison === when you want to compare both value and type.
  • Put the most likely case first to keep logic easy to follow.

Loops

What it is: A loop repeats a block of code. It helps you do the same task many times without writing the same lines again.

Why it is used (real-life example): If you want to show 10 product names, you do not want to write 10 echo lines. A loop can print them one by one.

Step-by-step
  • Pick a loop type: for is good when you know the count.
  • Set a start value (example: $i = 1).
  • Set a condition to keep looping (example: $i <= 5).
  • Change the value each time (example: $i++).
  • Put the code to repeat inside the braces { }.
Code example 1: for loop
<?php>
for ($i = 1; $i <= 5; $i++) {
echo "Item number: " . $i . "<br>";
}
?>

Explanation: $i starts at 1. The loop runs while $i is 5 or less. Each round increases $i by 1.

Code example 2: while loop
<?php>
$count = 3;
while ($count > 0) {
echo "Countdown: " . $count . "<br>";
$count--;
}
echo "Done!";
?>

Explanation: The loop checks the condition before each run. When $count becomes 0, it stops.

Common mistakes
  • Forgetting to change the counter, causing an infinite loop.
  • Using the wrong condition, like < instead of <=.
  • Putting ; right after for(...) by mistake, which makes the loop body empty.
Tips / best practices
  • Keep loop bodies small and easy to read.
  • Use clear counter names like $i for simple loops, or $index for clarity.
  • Add a safety limit if the loop depends on user input.

Functions

What it is: A function is a named block of code you can reuse. You can give it input (parameters) and get output (a return value).

Why it is used (real-life example): If you format prices many times (like $9.5 to $9.50), you can write one function and call it everywhere.

Step-by-step
  • Create a function with function name() { }.
  • Add parameters inside the parentheses if you need input.
  • Write the steps inside the braces.
  • Use return to send a result back.
  • Call the function by its name.
Code example 1: simple function
<?php>
function sayHello($name) {
return "Hello, " . $name . "!";
}

echo sayHello("Amina");
?>

Explanation: The function takes $name and returns a greeting string. echo prints it.

Code example 2: reusable calculation
<?php>
function addTax($price, $taxRate) {
$tax = $price * $taxRate;
$total = $price + $tax;
return $total;
}

$finalPrice = addTax(100, 0.15);
echo "Final price: " . $finalPrice;
?>

Explanation: $price is the base value. $taxRate is the percent as a decimal (15% is 0.15). The function returns the total.

Common mistakes
  • Forgetting to return a value when you expect output.
  • Using a variable inside the function that was never passed in.
  • Naming functions with unclear names like doStuff().
Tips / best practices
  • Keep one function doing one job.
  • Use clear names like formatPrice or calculateTotal.
  • Add simple input checks when needed (for example, make sure price is not negative).

Scope

What it is: Scope means where a variable can be used. Some variables work only inside a function. Others can be available outside.

Why it is used (real-life example): You may have a global setting like a site name. But inside a function, you might use a temporary variable for a loop. Scope keeps things from mixing by accident.

Step-by-step
  • A variable created outside a function is in the global scope.
  • A variable created inside a function is in the local scope (only inside that function).
  • To use a global variable inside a function, you can use the global keyword.
  • A better approach is often to pass values into the function as parameters.
Code example 1: local vs global
<?php>
$siteName = "My Shop";

function showSite() {
$message = "Welcome!";
echo $message;
}

showSite();
echo "<br>" . $siteName;
?>

Explanation: $message exists only inside showSite(). $siteName is outside and can be used outside.

Code example 2: using global inside a function
<?php>
$counter = 0;

function increaseCounter() {
global $counter;
$counter = $counter + 1;
}

increaseCounter();
increaseCounter();
echo "Counter: " . $counter;
?>

Explanation: global $counter; tells PHP to use the global variable, not create a new local one.

Common mistakes
  • Trying to use a local variable outside the function where it was created.
  • Forgetting global and thinking the global variable will change.
  • Overusing global variables, which makes code hard to test and debug.
Tips / best practices
  • Prefer passing values into functions instead of using global.
  • Use clear variable names to avoid confusion between global and local values.
  • Keep variables as local as possible to reduce bugs.

Forms

What it is: A form is HTML inputs (like a text box and a button) that send data to your PHP script.

Why it is used (real-life example): When you log in, sign up, or search on a website, you usually send a form to the server.

Step-by-step
  • Create an HTML form with a method: GET or POST.
  • Point the form action to a PHP file.
  • In PHP, read values from $_GET or $_POST.
  • Check if a value exists before using it.
  • Clean the value before showing it on the page.
Code example 1: GET form
<!-- search.html -->
<form action="search.php" method="get">
  <input type="text" name="q" placeholder="Search...">
  <button type="submit">Go</button>
</form>

<?php
// search.php
$q = $_GET['q'] ?? '';
$qSafe = htmlspecialchars($q, ENT_QUOTES, 'UTF-8');
echo 'You searched for: ' . $qSafe;
?>

Explanation: The form sends the input named q in the URL. In PHP, we use $_GET to read it. We also use htmlspecialchars so the user cannot inject HTML.

Code example 2: POST form
<!-- contact.html -->
<form action="contact.php" method="post">
  Name: <input type="text" name="name">
  <button type="submit">Send</button>
</form>

<?php
// contact.php
$name = $_POST['name'] ?? '';
$name = trim($name);
if ($name === '') {
  echo 'Please enter your name.';
} else {
  echo 'Thanks, ' . htmlspecialchars($name, ENT_QUOTES, 'UTF-8') . '!';
}
?>

Explanation: POST sends data in the request body (not in the URL). We use trim to remove extra spaces, then we validate it.

Common mistakes
  • Using $_GET while the form uses POST (or the opposite).
  • Assuming a value exists and getting “Undefined index”. Use ?? or isset.
  • Printing user input without htmlspecialchars (XSS risk).
Tips / best practices
  • Use POST for sensitive data like passwords.
  • Always validate and sanitize input before using it.
  • Show friendly error messages when something is missing.

Sessions

What it is: A session is a way to store small data on the server for one user, across many pages.

Why it is used (real-life example): After a user logs in, you keep them logged in while they visit other pages.

Step-by-step
  • Start the session with session_start() at the top of the PHP file.
  • Write values into $_SESSION.
  • Read values from $_SESSION on the next pages.
  • To log out, remove session values and destroy the session.
Code example 1: Save a value
<?php
// set_session.php
session_start();
$_SESSION['username'] = 'maria';
echo 'Session saved for username.';
?>

Explanation: session_start() connects PHP to the user’s session. Then we store username on the server.

Code example 2: Read and log out
<?php
// dashboard.php
session_start();
$username = $_SESSION['username'] ?? null;
if ($username === null) {
  echo 'You are not logged in.';
} else {
  echo 'Welcome, ' . htmlspecialchars($username, ENT_QUOTES, 'UTF-8') . '!';
}

// logout.php
session_start();
$_SESSION = [];
session_destroy();
echo 'You are logged out.';
?>

Explanation: We read the value safely using ??. For logout, we clear the session array and call session_destroy().

Common mistakes
  • Forgetting session_start() (session values will not work).
  • Calling session_start() after output (can cause header errors).
  • Storing large data in sessions (it slows things down).
Tips / best practices
  • Store only small identifiers (like user id), not big arrays.
  • Regenerate session id after login using session_regenerate_id(true).
  • Always escape session values when printing them into HTML.

Cookies

What it is: A cookie is a small piece of text stored in the user’s browser. It is sent back to the server on future requests.

Why it is used (real-life example): Remembering a user’s language choice or keeping a “remember me” setting (with care).

Step-by-step
  • Set a cookie with setcookie() before any output.
  • Read a cookie from $_COOKIE on later requests.
  • Delete a cookie by setting it again with an old expiration time.
Code example 1: Set and read a cookie
<?php
// set_cookie.php
$oneWeek = time() + (7 * 24 * 60 * 60);
setcookie('theme', 'dark', $oneWeek, '/');
echo 'Cookie set. Refresh or open read_cookie.php.';
?>

<?php
// read_cookie.php
$theme = $_COOKIE['theme'] ?? 'light';
echo 'Theme is: ' . htmlspecialchars($theme, ENT_QUOTES, 'UTF-8');
?>

Explanation: setcookie tells the browser to store the cookie. On the next request, the browser sends it back and you can read it in $_COOKIE.

Code example 2: Delete a cookie
<?php
// delete_cookie.php
setcookie('theme', '', time() - 3600, '/');
echo 'Cookie deleted.';
?>

Explanation: Setting an expiration time in the past tells the browser to remove the cookie.

Common mistakes
  • Calling setcookie() after printing output (causes header errors).
  • Storing secrets in cookies (users can read and change them).
  • Not using a default value when a cookie does not exist.
Tips / best practices
  • Only store non-sensitive settings (like theme or language).
  • When needed, set secure options (like httponly and secure) using the options array in newer PHP versions.
  • Always escape cookie values before printing.

File Handling

What it is: File handling means reading from a file and writing to a file using PHP. A file can store notes, logs, settings, or exported data.

Why it is used (real-life example): You can save contact form messages into a text file so you can review them later, even without a database.

Step-by-step
  • Choose a file path (example: data/messages.txt).
  • Open the file with the correct mode: read (r), write (w), append (a).
  • Write or read content.
  • Close the file to free resources.
Code example 1: Append a line to a log file
<?php>
$path = __DIR__ . "/data/visits.log";
$line = date("Y-m-d H:i:s") . " - Visit from " . $_SERVER["REMOTE_ADDR"] . "\n";

$handle = fopen($path, "a");
if ($handle === false) {
die("Cannot open file");
}

fwrite($handle, $line);
fclose($handle);
echo "Saved";
?>

Explanation: fopen opens the file in append mode, fwrite adds the text, and fclose closes it.

Code example 2: Read a file safely
<?php>
$path = __DIR__ . "/data/visits.log";

if (!file_exists($path)) {
echo "No log yet.";
exit;
}

$content = file_get_contents($path);
echo "<pre>" . htmlspecialchars($content) . "</pre>";
?>

Explanation: file_get_contents reads the whole file. htmlspecialchars prevents the browser from running any text as HTML.

Common mistakes
  • Using w mode by accident (it deletes the old file content).
  • Not checking if the file exists before reading.
  • Forgetting to close the file handle.
  • Showing raw file content without escaping it in HTML pages.
Tips / best practices
  • Store files outside the public web folder when possible.
  • Use __DIR__ to build safe paths.
  • Prefer file_get_contents and file_put_contents for simple tasks.
  • Always validate and escape user text before saving or displaying.

JSON

What it is: JSON is a simple text format for sharing data. It looks like arrays and objects. PHP can convert arrays to JSON and JSON back to arrays.

Why it is used (real-life example): A JavaScript app may call your PHP page and expect JSON, like a list of products or user settings.

Step-by-step
  • Create a PHP array with your data.
  • Convert it to JSON using json_encode.
  • When receiving JSON, read the text and parse it with json_decode.
  • Check for errors if the JSON is not valid.
Code example 1: Send JSON output
<?php>
header("Content-Type: application/json; charset=utf-8");

$user = [
"id" => 7,
"name" => "Mina",
"active" => true
];

echo json_encode($user);
?>

Explanation: The header tells the browser it is JSON. json_encode turns the array into JSON text.

Code example 2: Read JSON and convert to array
<?php>
$json = '{"product":"Book","qty":2}';
$data = json_decode($json, true);

if ($data === null && json_last_error() !== JSON_ERROR_NONE) {
die("Bad JSON: " . json_last_error_msg());
}

echo "Product: " . $data["product"] . ", Qty: " . $data["qty"];
?>

Explanation: json_decode with true returns an associative array. We check errors to avoid using broken data.

Common mistakes
  • Forgetting true and then trying to use array syntax on an object.
  • Not checking json_last_error after decoding.
  • Echoing extra text before JSON (it breaks API responses).
  • Using single quotes around JSON keys (JSON requires double quotes).
Tips / best practices
  • Always set Content-Type: application/json when returning JSON.
  • Use clear data shapes (same keys every time).
  • Validate incoming data before saving it or using it.
  • For readable output during learning, try json_encode($data, JSON_PRETTY_PRINT).

Exceptions

What it is: An exception is a special error you can throw and then catch. It helps you stop a bad action and show a friendly message instead of a broken page.

Why it is used (real-life example): If a user uploads a file that is too big, you can throw an exception and tell the user what to fix.

Step-by-step
  • Put risky code inside try.
  • If something is wrong, use throw new Exception(...).
  • Handle it in catch and show a safe message.
  • Use finally for code that must run (like closing resources).
Code example 1: Basic try/catch
<?php>
function divide($a, $b) {
if ($b === 0) {
throw new Exception("You cannot divide by zero");
}
return $a / $b;
}

try {
echo divide(10, 0);
} catch (Exception $e) {
echo "Error: " . $e->getMessage();
}
?>

Explanation: throw stops the function and sends the problem to catch. The page keeps working and shows a clear message.

Code example 2: finally for cleanup
<?php>
$handle = null;

try {
$path = __DIR__ . "/data/sample.txt";
$handle = fopen($path, "r");
if ($handle === false) {
throw new Exception("Cannot open the file");
}
$text = fread($handle, 50);
echo htmlspecialchars($text);
} catch (Exception $e) {
echo "Problem: " . $e->getMessage();
} finally {
if (is_resource($handle)) {
fclose($handle);
}
}
?>

Explanation: finally runs even if an error happens. This is good for closing files and cleaning up.

Common mistakes
  • Catching exceptions but hiding them without logging anything.
  • Throwing very generic messages that do not help the user.
  • Using exceptions for normal flow (like simple if checks).
  • Showing detailed server errors to users (can expose private info).
Tips / best practices
  • Use clear messages for users, and log technical details for developers.
  • Validate input early to prevent exceptions later.
  • Catch specific exception types when you can (more control).
  • Keep try blocks small so it is easy to see what may fail.

Classes

What it is: A class is a blueprint for creating objects. It groups data (properties) and actions (methods) in one place.

Why it is used (real-life example): If you build a website with users, you can make a User class to store user data (name, email) and actions (display profile). This keeps your code organized.

Step-by-step
  • Create a class with class Name.
  • Add properties to store data.
  • Add methods to do actions.
  • Create an object using new.
  • Use -> to access properties and methods.
Code example 1: Simple class and object
<?php>
class User {
public $name;

public function sayHello() {
return "Hello, I am " . $this->name;
}
}

$user = new User();
$user->name = "Amina";
echo $user->sayHello();
?>

Explanation: $name is a property. sayHello() is a method. $this means “this object”.

Code example 2: Using a constructor
<?php>
class Product {
public $title;

public function __construct($title) {
$this->title = $title;
}
}

$p1 = new Product("Notebook");
echo $p1->title;
?>

Explanation: __construct runs automatically when you create the object.

Common mistakes
  • Forgetting $this-> when using properties inside methods.
  • Using . instead of -> for object access.
  • Misspelling method or property names (PHP will not fix spelling for you).
Tips / best practices
  • Use classes to group related code. It makes code easier to read.
  • Keep one class focused on one main job (like User or Product).
  • Start with simple classes before adding more features.

Objects

What it is: An object is a real created thing from a class. It holds its own values and can run its methods.

Why it is used (real-life example): If you have many users, each user is an object. Each object can have different data, like different names and emails.

Step-by-step
  • Create an object with new ClassName().
  • Set property values for that object.
  • Call methods using ->.
  • Create more objects from the same class when you need more “instances”.
Code example 1: Two objects from one class
<?php>
class Dog {
public $name;

public function bark() {
return $this->name . " says woof";
}
}

$d1 = new Dog();
$d1->name = "Max";

$d2 = new Dog();
$d2->name = "Luna";

echo $d1->bark();
echo " | ";
echo $d2->bark();
?>

Explanation: $d1 and $d2 are separate objects. Changing one does not change the other.

Code example 2: Copying object references
<?php>
class Counter {
public $value = 0;
}

$c1 = new Counter();
$c2 = $c1; // both point to the same object

$c2->value = 5;
echo $c1->value; // prints 5
?>

Explanation: In PHP, assigning an object to another variable usually copies the reference. That means both variables can refer to the same object.

Common mistakes
  • Thinking $c2 = $c1 creates a new separate object (it usually does not).
  • Trying to access object parts like an array (using []) when it is not an array.
  • Forgetting to create the object before using it (calling a method on null).
Tips / best practices
  • Create a new object when you need separate state: use new again.
  • Use clear variable names like $user or $product to show what the object represents.
  • When unsure, var_dump($obj) can help you see the object structure while learning.

Inheritance

What it is: Inheritance lets one class (child) reuse and extend another class (parent). The child gets the parent’s properties and methods.

Why it is used (real-life example): You might have a general Account class, and then AdminAccount and CustomerAccount can reuse common code like username handling, but add their own features.

Step-by-step
  • Create a parent class with shared code.
  • Create a child class using extends.
  • Add new methods or properties in the child class.
  • Optionally override a parent method to change behavior.
  • Use parent::methodName() if you still want to run the parent method.
Code example 1: Reusing methods with extends
<?php>
class Account {
public $username;

public function __construct($username) {
$this->username = $username;
}

public function label() {
return "User: " . $this->username;
}
}

class AdminAccount extends Account {
public function isAdmin() {
return true;
}
}

$admin = new AdminAccount("root");
echo $admin->label();
?>

Explanation: AdminAccount automatically gets label() from Account.

Code example 2: Overriding a method
<?php>
class Message {
public function format($text) {
return "MSG: " . $text;
}
}

class HtmlMessage extends Message {
public function format($text) {
$base = parent::format($text);
return "<strong>" . $base . "</strong>";
}
}

$m = new HtmlMessage();
echo $m->format("Saved");
?>

Explanation: The child method replaces the parent method, but we still call the parent using parent::format().

Common mistakes
  • Using inheritance when classes are not really related. This makes code confusing.
  • Forgetting that overridden methods change behavior everywhere you use the child class.
  • Trying to access private parent properties directly from the child (private means only the parent can use it).
Tips / best practices
  • Use inheritance only when the child “is a” type of the parent (AdminAccount is an Account).
  • Keep parent classes small and focused on shared behavior.
  • When overriding, keep method names and parameter order the same to avoid confusion.