Topics Covered in This PHP & MySQL Tutorial:
Functions, Arguments, Objects & Properties, Objects & Methods, Private Properties, Creating Classes That Extend Classes
Exercise Overview
In this comprehensive exercise, you'll master the fundamental building blocks of object-oriented PHP programming. We'll start with functions and arguments to establish reusable code patterns, then progress to creating robust objects with properties and methods. You'll learn the critical distinction between public and private properties for proper encapsulation, and discover how to extend classes to build scalable, maintainable applications. These concepts form the backbone of modern PHP development and are essential for any serious web developer.
Functions
Functions in PHP are self-contained code routines that encapsulate specific logic and can be invoked anywhere in your application. They're the foundation of clean, reusable code architecture.
In your code editor, open objects.php from the phpclass folder. Notice this has the same basic HTML structure as other PHP files we've worked with.
In between the
<body>tags, add PHP tags, as shown:<?php ?>Let's create a practical function that generates billing calculations for a lawyer's fees. Add the following bold code to define a function:
<?php function get_lawyer_bill() ?>To define a function, you start with the keyword
function, followed by the name of the function, followed by parentheses ().Function naming follows specific conventions that ensure code readability and prevent conflicts:
- They can include alphabetical or numerical characters.
- They cannot begin with a number.
- They cannot include spaces, but can use underscores for readability.
Add variables to the function, as shown in bold:
<?php function get_lawyer_bill() { $hourly_rate = 100; $hours = 3; } ?>Like if/else statements, functions use curly braces {} to define their scope. When a function is called, all code between these braces executes in sequence.
Add the following bold code to complete the function logic:
<?php function get_lawyer_bill() { $hourly_rate = 100; $hours = 3; return $hourly_rate * $hours; } ?>The
returnkeyword specifies the value that the function outputs when called. This value can be printed on-screen, stored in a database, assigned to variables, or used in further calculations. Here, we're returning the total billing amount.Save the page and then navigate in your browser to:
- Mac: localhost:8888/phpclass/objects.php
- Windows: localhost/phpclass/objects.php
The page appears blank because defining a function merely creates it—functions remain dormant until explicitly called. Think of it as writing a recipe versus actually cooking the meal.
Switch back to your code editor.
Add the following bold code to invoke the function:
<?php function get_lawyer_bill() { $hourly_rate = 100; $hours = 3; return $hourly_rate * $hours; } echo get_lawyer_bill(); ?>Here, we've called the function by name. The
echostatement displays the returned value on screen.Save the page, then refresh objects.php in your browser. Now you should see the value 300.
Return to your code editor.
Functions excel at reusability—you can call them as many times as needed without rewriting logic. Add the bold code to demonstrate this:
<?php function get_lawyer_bill() { $hourly_rate = 100; $hours = 3; return $hourly_rate * $hours; } echo get_lawyer_bill(); echo '<br>'; echo get_lawyer_bill(); echo '<br>'; echo get_lawyer_bill(); echo '<br>'; ?>This calls the same function three times with line breaks between each output, demonstrating code reusability.
Save the file, refresh the browser, and reload objects.php. You'll see 300 displayed three times, each on a separate line.
Functions can include alphabetical or numerical characters, cannot begin with a number, and cannot include spaces but can use underscores for readability.
Creating Your First Function
Define the Function
Start with the keyword 'function' followed by the function name and parentheses
Add Function Body
Place your code logic between curly braces that will execute when called
Return a Value
Use the 'return' keyword to specify what value should be passed out of the function
Call the Function
Use the function name with echo to display results or store in variables
Arguments
Arguments transform functions from static code blocks into dynamic, flexible tools. They allow external values to be passed into functions, making each function call potentially unique and far more powerful.
Let's enhance our
get_lawyer_billfunction by making the hourly rate and hours configurable through arguments. Add the following bold code:function get_lawyer_bill($hourly_rate, $hours) { $hourly_rate = 100; $hours = 3; return $hourly_rate * $hours; }Since we're now receiving these values as arguments, we can remove the hardcoded variable assignments. Delete the variable definitions so you're left with:
function get_lawyer_bill($hourly_rate, $hours) { return $hourly_rate * $hours; }We no longer need the third function call since we're about to demonstrate different argument values. Select the following code and delete it:
echo '<br>'; echo get_lawyer_bill(); echo '<br>';Now let's pass different arguments to simulate bills for two different lawyers with varying rates and hours. Update the remaining function calls:
echo get_lawyer_bill(100,3); echo '<br>'; echo get_lawyer_bill(120,2);Save the file, then refresh objects.php in your browser.
Observe the calculated results: 300 and 240 respectively! This demonstrates the true power of arguments—the same function now handles multiple scenarios with different inputs, making your code both versatile and maintainable. Instead of writing separate functions for each lawyer, you've created one flexible solution.
Return to your code editor.
Arguments can include default values using an equals sign (=). When an argument is omitted during the function call, PHP automatically uses the default value—a powerful feature for creating flexible APIs.
Add a default value for hours to handle cases where only the hourly rate is provided:
function get_lawyer_bill($hourly_rate, $hours = 1) { return $hourly_rate * $hours; }Update the function calls to demonstrate default parameter usage:
echo get_lawyer_bill(200); echo '<br>'; echo get_lawyer_bill(200, 2);Save the file, refresh the browser, and reload objects.php. The first result shows 200 (200 × 1 hour default), while the second shows 400 (200 × 2 hours specified). This pattern is common in professional PHP applications where sensible defaults improve usability.
Function Calls: With vs Without Arguments
| Feature | Without Arguments | With Arguments |
|---|---|---|
| Flexibility | Fixed values only | Dynamic inputs |
| Reusability | Limited | High |
| Code Efficiency | Requires multiple functions | One function, multiple uses |
| Example Output | Always 300 | 300, 240, 200, 400 |
Lawyer Bill Calculations from Tutorial
Objects & Properties
PHP objects represent a more sophisticated approach to data organization than simple variables or arrays. They bundle related data and functionality together, creating logical, maintainable code structures that mirror real-world entities.
Let's start fresh with objects. In your code editor, delete the entire function so you're left with empty PHP tags:
<?php ?>PHP's most basic object type is stdClass (standard class). Create a new object with this code:
<?php $lawyer = new stdClass(); ?>This instantiates a new
stdClassobject calledlawyer. Thenewkeyword is required for creating any PHP object instance.Notice the
stdClassnaming convention. This CamelCase format (capitalizing each word) is standard for PHP class names and promotes code readability across development teams.Now let's give our lawyer object a name property:
<?php $lawyer = new stdClass(); $lawyer->name = 'Juanita Jones'; ?>Variables attached to objects are called properties. The arrow operator
->connects the object to its property, establishing thatnamebelongs specifically to ourlawyerobject.Let's expand our lawyer object with additional properties that represent real-world attributes:
<?php $lawyer = new stdClass(); $lawyer->name = 'Juanita Jones'; $lawyer->hourly_rate = 100; $lawyer->specialties = ['Family Law', 'Tax Law']; ?>Object properties accept any data type—strings, integers, arrays, or even other objects. This flexibility makes objects excellent containers for complex data structures.
Let's output some information about our lawyer:
<?php $lawyer = new stdClass(); $lawyer->name = 'Juanita Jones'; $lawyer->hourly_rate = 100; $lawyer->specialties = ['Family Law', 'Tax Law']; echo $lawyer->name. ' charges $'. $lawyer->hourly_rate. ' per hour.'; echo '<br><br>'; ?>This demonstrates how to access and display object properties, creating readable output from structured data.
Use
print_r()to examine the complete object structure:<?php $lawyer = new stdClass(); $lawyer->name = 'Juanita Jones'; $lawyer->hourly_rate = 100; $lawyer->specialties = ['Family Law', 'Tax Law']; echo $lawyer->name. ' charges $'. $lawyer->hourly_rate. ' per hour.'; echo '<br><br>'; echo "<pre>"; print_r($lawyer); echo "</pre>"; ?>The
print_r()function reveals the internal structure of any variable. The<pre>tags preserve formatting, making the output more readable—a valuable debugging technique.Save the file, refresh your browser, and reload objects.php. You'll see Juanita Jones charges $100 per hour. followed by the detailed object structure showing all properties and their values.
PHP class names use CamelCase formatting, stringing words together while capitalizing each word. The first letter may be capital or lowercase.
Objects vs Multidimensional Arrays
Objects & Methods
While objects with properties provide better data organization than arrays, their true power emerges when you add methods—functions that belong to and operate on the object's data. This combination of data and behavior is the essence of object-oriented programming.
Return to your code editor.
Delete all the existing
lawyerobject code, leaving empty PHP tags:<?php ?>Let's create a custom Lawyer class with its own properties and methods:
<?php class Lawyer { } ?>Class declarations begin with the
classkeyword followed by the class name. Unlike most PHP variables, class names use CamelCase and typically start with a capital letter—a convention that distinguishes classes from variables and functions.Add properties to define what data each Lawyer object will contain:
<?php class Lawyer { public $name, $hourly_rate; } ?>The
publickeyword means these properties can be directly accessed and modified from outside the class, similar to stdClass objects.Now add a method that calculates billing amounts:
<?php class Lawyer { public $name, $hourly_rate; function get_bill($hours) { } } ?>This creates a
get_billmethod that accepts an$hoursargument. Since$hourly_rateis already a property of the Lawyer class, we don't need to pass it as an argument.Implement the billing calculation using the special
$thisvariable:class Lawyer { public $name, $hourly_rate; function get_bill($hours) { $total = $this->hourly_rate * $hours; } }The
$thisvariable is a reference to the current object instance.$this->hourly_rateaccesses the hourly_rate property of the specific Lawyer object calling this method.Complete the method by returning a formatted billing message:
class Lawyer { public $name, $hourly_rate; function get_bill($hours) { $total = $this->hourly_rate * $hours; return "You owe ". $this->name. ' $'. $total. '.'; } }Create an instance of the Lawyer class—defining a class is like creating a blueprint, but we need to build an actual object to use it:
function get_bill($hours) { $total = $this->hourly_rate * $hours; return "You owe ". $this->name. ' $'. $total. '.'; } } $alfred = new Lawyer();Set the properties for our new lawyer object:
$alfred = new Lawyer(); $alfred->name = 'Alfred Frank'; $alfred->hourly_rate = 50;Call the method and display the result:
$alfred = new Lawyer(); $alfred->name = 'Alfred Frank'; $alfred->hourly_rate = 50; echo $alfred->get_bill(2);This demonstrates method invocation: we create the Lawyer object (
$alfred), set its properties, then call theget_billmethod with 2 hours as the argument.Save the file, refresh your browser, and reload objects.php. You should see You owe Alfred Frank $100.
Return to your code editor.
One of the most powerful aspects of classes is creating multiple instances with different data. Add a second lawyer with different rates:
$alfred = new Lawyer(); $alfred->name = 'Alfred Frank'; $alfred->hourly_rate = 50; echo $alfred->get_bill(2); echo '<br>'; $juanita = new Lawyer();This creates a completely separate Lawyer instance that can have entirely different property values while using the same class methods.
Configure the second lawyer and generate her bill:
echo '<br>'; $juanita = new Lawyer(); $juanita->name = 'Juanita Jones'; $juanita->hourly_rate = 150; echo $juanita->get_bill(5);Save the file, refresh the browser, and reload the page. You'll see both billing messages: You owe Alfred Frank $100. and You owe Juanita Jones $750. This demonstrates the scalability of object-oriented design—one class definition supporting multiple object instances with different data.
Return to your code editor.
The keyword 'new' is always used to initialize a new PHP object of any kindBuilding a Custom Class
Declare the Class
Use 'class' keyword followed by CamelCase class name in curly braces
Define Properties
Add public or private variables that will store object data
Create Methods
Write functions inside the class that can access object properties using '$this'
Instantiate Objects
Create new instances using 'new' keyword and set property values
Private Properties
Professional PHP development relies heavily on private properties to create secure, maintainable code. Unlike public properties that can be directly accessed and modified, private properties require controlled access through methods, preventing accidental data corruption and enforcing business rules.
Change the property visibility from public to private around line 12:
private $name, $hourly_rate;Save the file, refresh your browser, and reload the page. You'll see either a blank page or an error message: Cannot access private property Lawyer::$name.
Return to your code editor. The error occurs around line 20 where we attempted to directly set the private
$nameproperty.Private properties require a different approach—they're typically set through methods, often during object creation. This pattern provides better control over data validation and maintains object integrity.
Clean up the code by deleting lines 20–30, so you have:
$alfred = new Lawyer(); ?>Add a constructor method that will automatically run when new objects are created:
class Lawyer { private $name, $hourly_rate; function __construct() function get_bill($hours) {The
__constructmethod (note the two underscores) is a special function that PHP automatically calls whenever you create a new instance of a class. This is where you typically initialize object properties.Configure the constructor to accept the necessary parameters:
function __construct($name, $hourly_rate)Implement the constructor to set the private properties:
function __construct($name, $hourly_rate) { $this->name = $name; $this->hourly_rate = $hourly_rate; }This pattern ensures that objects are created with valid data and that private properties are properly initialized.
Update the object creation to pass the required parameters:
$alfred = new Lawyer('Alfred Frank', 50); ?>Now the constructor receives these values and uses them to initialize the private properties securely.
Generate and display the billing information:
$alfred = new Lawyer('Alfred Frank', 50); echo $alfred->get_bill(10); ?>Save the file, refresh your browser, and reload the page. You should see You owe Alfred Frank $500. The private properties are now properly encapsulated and can only be set through the controlled constructor method.
Public vs Private Properties
| Feature | Public Properties | Private Properties |
|---|---|---|
| Access Level | Easily accessed externally | Only accessible within class |
| Setting Values | Direct assignment | Through methods only |
| Security | Less controlled | More secure and controlled |
| Common Usage | Simple objects | Professional PHP applications |
The __construct method requires two underscores before 'construct' and is automatically called when creating new object instances with the 'new' keyword.
Creating Classes That Extend Classes
Class inheritance allows you to build upon existing classes, adding new functionality while preserving proven code. This powerful feature promotes code reuse and creates logical hierarchies that reflect real-world relationships.
Replace lines 24–25 with a new class that extends our Lawyer class:
class BillboardLawyer extends Lawyer { } ?>The
extendskeyword tells PHP that BillboardLawyer inherits all properties and methods from the Lawyer class. We don't need to redefine the name, hourly_rate, or any existing functionality.
Extended classes automatically inherit all properties and methods from their parent class without needing to redefine existing functionality.
Class Extension Process
Create Base Class
Define original Lawyer class with basic properties and methods
Extend the Class
Use 'extends' keyword to create BillboardLawyer that builds on Lawyer
Override Methods
Redefine specific methods while keeping others unchanged
Call Parent Methods
Use 'parent::method_name()' to access original functionality