Skip to main content
March 23, 2026Noble Desktop Publishing Team/12 min read

Functions & Objects: Free PHP & MySQL Tutorial

Master PHP Functions and Object-Oriented Programming Fundamentals

Core Concepts You'll Master

Functions & Arguments

Learn to create reusable code blocks that accept dynamic inputs for flexible programming solutions.

Objects & Properties

Understand how to structure data using object-oriented principles with properties and methods.

Class Inheritance

Discover how to extend existing classes to build upon functionality without rewriting code.

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.

  1. 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.

  2. In between the <body> tags, add PHP tags, as shown:

    <?php
    
    ?>
  3. 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.
  4. 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.

  5. 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 return keyword 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.

  6. 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.

  7. Switch back to your code editor.

  8. 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 echo statement displays the returned value on screen.

  9. Save the page, then refresh objects.php in your browser. Now you should see the value 300.

  10. Return to your code editor.

  11. 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.

  12. Save the file, refresh the browser, and reload objects.php. You'll see 300 displayed three times, each on a separate line.

Function Naming Best Practices

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

1

Define the Function

Start with the keyword 'function' followed by the function name and parentheses

2

Add Function Body

Place your code logic between curly braces that will execute when called

3

Return a Value

Use the 'return' keyword to specify what value should be passed out of the function

4

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.

  1. Let's enhance our get_lawyer_bill function 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;
    }
  2. 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;
    }
  3. 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>';
  4. 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);
  5. Save the file, then refresh objects.php in your browser.

  6. 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.

  7. 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.

  1. 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;
    }
  2. Update the function calls to demonstrate default parameter usage:

    echo get_lawyer_bill(200);
    echo '<br>';
    echo get_lawyer_bill(200, 2);
  3. 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

FeatureWithout ArgumentsWith Arguments
FlexibilityFixed values onlyDynamic inputs
ReusabilityLimitedHigh
Code EfficiencyRequires multiple functionsOne function, multiple uses
Example OutputAlways 300300, 240, 200, 400
Recommended: Arguments make functions significantly more versatile and reduce code duplication

Lawyer Bill Calculations from Tutorial

Lawyer 1 (100/hr, 3hrs)
300
Lawyer 2 (120/hr, 2hrs)
240
Default (200/hr, 1hr)
200
Custom (200/hr, 2hrs)
400

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.

  1. Let's start fresh with objects. In your code editor, delete the entire function so you're left with empty PHP tags:

    <?php
    
    ?>
  2. 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 stdClass object called lawyer. The new keyword is required for creating any PHP object instance.

    Notice the stdClass naming convention. This CamelCase format (capitalizing each word) is standard for PHP class names and promotes code readability across development teams.

  3. 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 that name belongs specifically to our lawyer object.

  4. 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.

  5. 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.

  6. 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.

  7. 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.

CamelCase Convention

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

Pros
Can contain methods (functions) in addition to data
More structured approach to organizing related information
Support for access control with public/private properties
Enable inheritance and code reusability
Cleaner syntax with arrow notation
Cons
Slightly more complex syntax than arrays
Require understanding of object-oriented concepts
May be overkill for simple data storage needs

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.

  1. Return to your code editor.

  2. Delete all the existing lawyer object code, leaving empty PHP tags:

    <?php
    
    ?>
  3. Let's create a custom Lawyer class with its own properties and methods:

    <?php
    
       class Lawyer {
       }
    
    ?>

    Class declarations begin with the class keyword 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.

  4. Add properties to define what data each Lawyer object will contain:

    <?php
    
       class Lawyer {
          public $name, $hourly_rate;
       }
    
    ?>

    The public keyword means these properties can be directly accessed and modified from outside the class, similar to stdClass objects.

  5. Now add a method that calculates billing amounts:

    <?php
    
       class Lawyer {
          public $name, $hourly_rate;
    
          function get_bill($hours) {
    
          }
       }
    
    ?>

    This creates a get_bill method that accepts an $hours argument. Since $hourly_rate is already a property of the Lawyer class, we don't need to pass it as an argument.

  6. Implement the billing calculation using the special $this variable:

    class Lawyer {
       public $name, $hourly_rate;
    
       function get_bill($hours) {
          $total = $this->hourly_rate * $hours;
       }
    }

    The $this variable is a reference to the current object instance. $this->hourly_rate accesses the hourly_rate property of the specific Lawyer object calling this method.

  7. 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. '.';
       }
    }
  8. 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();
  9. Set the properties for our new lawyer object:

    $alfred = new Lawyer();
    $alfred->name = 'Alfred Frank';
    $alfred->hourly_rate = 50;
  10. 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 the get_bill method with 2 hours as the argument.

  11. Save the file, refresh your browser, and reload objects.php. You should see You owe Alfred Frank $100.

  12. Return to your code editor.

  13. 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.

  14. 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);
  15. 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.

  16. Return to your code editor.

The keyword 'new' is always used to initialize a new PHP object of any kind
Essential concept for creating object instances in PHP

Building a Custom Class

1

Declare the Class

Use 'class' keyword followed by CamelCase class name in curly braces

2

Define Properties

Add public or private variables that will store object data

3

Create Methods

Write functions inside the class that can access object properties using '$this'

4

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.

  1. Change the property visibility from public to private around line 12:

    private $name, $hourly_rate;
  2. 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.

  3. Return to your code editor. The error occurs around line 20 where we attempted to directly set the private $name property.

    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.

  4. Clean up the code by deleting lines 20–30, so you have:

    $alfred = new Lawyer();
    
    ?>
  5. 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 __construct method (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.

  6. Configure the constructor to accept the necessary parameters:

    function __construct($name, $hourly_rate)
  7. 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.

  8. 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.

  9. Generate and display the billing information:

    $alfred = new Lawyer('Alfred Frank', 50);
    echo $alfred->get_bill(10);
    
    ?>
  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

FeaturePublic PropertiesPrivate Properties
Access LevelEasily accessed externallyOnly accessible within class
Setting ValuesDirect assignmentThrough methods only
SecurityLess controlledMore secure and controlled
Common UsageSimple objectsProfessional PHP applications
Recommended: Most professional PHP code uses private properties for better encapsulation and security
Constructor Method Requirements

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.

  1. Replace lines 24–25 with a new class that extends our Lawyer class:

    class BillboardLawyer extends Lawyer {
    }
    
    ?>

    The extends keyword 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.

Inheritance Benefits

Extended classes automatically inherit all properties and methods from their parent class without needing to redefine existing functionality.

Class Extension Process

Step 1

Create Base Class

Define original Lawyer class with basic properties and methods

Step 2

Extend the Class

Use 'extends' keyword to create BillboardLawyer that builds on Lawyer

Step 3

Override Methods

Redefine specific methods while keeping others unchanged

Step 4

Call Parent Methods

Use 'parent::method_name()' to access original functionality

Key Takeaways

1Functions in PHP are reusable code routines that can be called multiple times, making code more efficient and maintainable
2Arguments make functions flexible by allowing different values to be passed in each time the function is called
3Objects can store both data (properties) and functionality (methods), making them more powerful than simple arrays
4The '$this' variable allows methods within a class to reference the specific instance of that object
5Private properties provide better security and control compared to public properties, requiring methods to access values
6The '__construct' method automatically runs when creating new object instances and is commonly used to set initial property values
7Class inheritance using 'extends' allows new classes to build upon existing functionality without rewriting code
8The 'parent::' syntax enables extended classes to call methods from their parent class while adding new functionality

RELATED ARTICLES