Functions & Objects: Free PHP & MySQL Tutorial

Master the basics of PHP & MySQL through our comprehensive tutorial where we cover topics like functions, arguments, objects, properties, and methods, and explore the differences between public and private properties, and how to extend classes' functionality.

This exercise is excerpted from Noble Desktop’s past app development training materials and is compatible with iOS updates through 2021. To learn current skills in web development, check out our coding bootcamps in NYC and live online.

Topics Covered in This PHP & MySQL Tutorial:

Functions, Arguments, Objects & Properties, Objects & Methods, Private Properties, Creating Classes That Extend Classes

Exercise Overview

In this exercise, we’ll learn the basics of functions and how to use arguments within them. We’ll go over how to create objects with properties and methods. We’ll explore the differences between public and private properties, and additionally how to extend classes’ functionality.

Functions

Functions in PHP are code routines that can be called at any time.

SQL Bootcamp: Live & Hands-on, In NYC or Online, Learn From Experts, Free Retake, Small Class Sizes,  1-on-1 Bonus Training. Named a Top Bootcamp by Forbes, Fortune, & Time Out. Noble Desktop. Learn More.
  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. Say we’ve been working with a lawyer and want to generate a bill for their fees. We can create a function to do this. Add the following bold code to define a function:

    <?php
    
       function get_lawyer_bill()
    
    ?>

    To define a function, you start with the word function, followed by the name of the function, followed by parentheses ().

    There are some rules for naming functions:

    • They can include alphabetical or numerical characters.
    • They cannot begin with a number.
    • They cannot include spaces, but can use underscores.
  4. Add variables to the function, as shown in bold:

    <?php
    
       function get_lawyer_bill() {
          $hourly_rate = 100;
          $hours = 3;
       }
    
    ?>

    Similarly to if/else statements, any time functions are called, the code between the curly braces {} is executed.

  5. Add the following bold code:

    <?php
    
       function get_lawyer_bill() {
          $hourly_rate = 100;
          $hours = 3;
          return $hourly_rate * $hours;
       }
    
    ?>

    The keyword return specifies the value to be passed out of the function (printed on-screen, stored in a database, etc.). In this case, we want to return the hourly rate multiplied by the hours.

  6. Save the page and then in a browser go to:

    • Mac: localhost:8888/phpclass/objects.php
    • Windows: localhost/phpclass/objects.php

    The page is blank because functions don’t do anything unless they’re called. By defining the function we’ve made it possible to get the lawyer bill, but if we want to see anything, we need to call it.

  7. Switch back to your code editor.

  8. Add the following bold code:

    <?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 keyword echo will print it to the screen.

  9. Save the page, then go back to the browser and reload objects.php. Now you should see the value 300.

  10. Return to your code editor.

  11. One cool thing about functions is you can call them as many times as you want. To see this in action, add the bold code:

    <?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 will call the function three times and put a line break between each time.

  12. Save the file, go to the browser, and reload objects.php. Now you should see 300 print three times.

Arguments

Functions become more useful when arguments are passed in. Arguments are outside values that are sent into a function when it’s called. Arguments can vary each time a function is called. Arguments are placed between parentheses after the function name when defining a function.

  1. Let’s make our get_lawyer_bill function more flexible by making the hourly rate and hours variable. Add the following bold code:

    function get_lawyer_bill($hourly_rate, $hours) {
       $hourly_rate = 100;
       $hours = 3;
       return $hourly_rate * $hours;
    }
  2. We no longer need the code defining the variables within the function. Delete them so that you are left with the code shown:

    function get_lawyer_bill($hourly_rate, $hours) {
       return $hourly_rate * $hours;
    }
  3. Now we need to return the product of the two variables. First off, we don’t need that third function call. Select it, as shown in bold, and delete it:

    echo get_lawyer_bill();
    echo '<br>';
    echo get_lawyer_bill();
    echo '<br>';
    echo get_lawyer_bill();
    echo '<br>';
  4. Let’s try passing different arguments into the function at the same time. Say we have two lawyers, each with different hourly rates. Add the bold code:

    echo get_lawyer_bill(100,3);
    echo '<br>';
    echo get_lawyer_bill(120,2);
  5. Save the file, then go back to the browser and reload objects.php.

  6. Check out the results of each lawyer’s bill (300 and 240)! This makes our code much more reusable and versatile. As you can see, arguments allow for a lot of flexibility and help you reuse important logic without having to rewrite code multiple times.

  7. Return to your code editor.

Arguments can be provided with default values by including an equals sign (=). In the case that the argument is omitted, the default will be used.

  1. Add the code shown in bold to make the default number of hours equal to 1:

    function get_lawyer_bill($hourly_rate, $hours = 1) {
       return $hourly_rate * $hours;
    }
  2. Edit the arguments as shown:

    function get_lawyer_bill($hourly_rate, $hours = 1) {
       return $hourly_rate * $hours;
    }
    echo get_lawyer_bill(200);
    echo '<br>';
    echo get_lawyer_bill(200, 2);
  3. Save the file, go to the browser, and reload objects.php. The first number that prints is 200. Because we didn’t specify the hours, it defaulted to 1-hour. The second number, 400, is the result of 200 X 2.

Objects & Properties

PHP objects are code constructs that can contain information, similarly to how multidimensional arrays do. Let’s start by creating a simple object to see how it works.

  1. In your code editor, delete the entire function so that you’re left with empty PHP tags:

    <?php
    
    ?>
  2. The most basic object type in PHP is called stdClass (standard class). Type the bold code:

    <?php
    
       $lawyer = new stdClass();
    
    ?>

    This creates a new stdClass basic object called lawyer. The keyword, new, is always used to initialize a new PHP object of any kind.

    Notice the way stdClass is written. This format of stringing words together while capitalizing each word is called CamelCase. PHP class names are written in CamelCase. Note that the first letter may be capital or lowercase.

  3. Now that we’ve created a new lawyer object, let’s give it a name. Add:

    <?php
    
       $lawyer = new stdClass();
       $lawyer->name = 'Juanita Jones';
    
    ?>

    Variables attached to objects are called properties. The -> is used to specify that name is a property of our lawyer object.

  4. Let’s assign properties for Juanita’s hourly rate and law specialties:

    <?php
    
       $lawyer = new stdClass();
       $lawyer->name = 'Juanita Jones';
       $lawyer->hourly_rate = 100;
       $lawyer->specialties = ['Family Law', 'Tax Law'];
    
    ?>

    Anything can become a property of an object. As you can see, we’ve just created a string, an integer, and an array as properties.

  5. Call the results by adding the bold code:

    <?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 will print that the lawyer object charges the hourly rate per hour followed by a couple line breaks.

  6. Use print_r() to examine the entire object by adding:

    <?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>";
    
    ?>

    Remember in the Arrays exercise, with the multidimensional array, print_r() dumped the entire array on screen. Above and below the print_r() function, we added <pre> tags so that the printed results will be preformatted (including the line breaks, tabs, etc. in the source code) and easier to read.

  7. Save the file, go to the browser, and reload objects.php. You should see Juanita Jones charges $100 per hour. followed by the code for the object and its properties.

Objects & Methods

At this point, the functionality we’ve explored is very similar to that of associative arrays. However, you should know that objects can do much more than what we’ve done so far! Objects can contain methods, which are functions inside of a class. Using methods within a class can make objects very powerful.

  1. Go back to your code editor.

  2. Delete all the lawyer object code so that you’re again left with empty PHP tags:

    <?php
    
    ?>
  3. Time to define our own class. Add a new Lawyer class, as shown in bold:

    <?php
    
       class Lawyer {
       }
    
    ?>

    Class declarations start with the keyword, class, followed by the class name. Unlike most variables in PHP, these are in CamelCase and will often start with a capital letter.

  4. Add some properties to the class:

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

    We declared public so that these properties can be easily accessed, set, and retrieved (like with stdClass objects).

  5. Add a method to get the lawyer bill:

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

    This creates a get_bill function with an $hours argument. The $hourly_rate will be a property of the Lawyer object, so it’s already known to us within the function, which is why we didn’t need to specify it as an argument.

  6. Now we need to compute the total. In order to get the $hourly_rate, we’ll need to refer to the object internally. This is because we want to refer to this particular instance of the Lawyer object from within the Lawyer class. To accomplish our goal, we can use the special variable, $this. Add the bold code:

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

    $this lets PHP know we’re referring to one specific instance of the Lawyer class. $this->hourly_rate gets the hourly rate of this specific lawyer.

  7. Add the following code to return a string saying how much and to whom you owe money:

    class Lawyer {
          public $name, $hourly_rate;
    
          function get_bill($hours) {
             $total = $this->hourly_rate * $hours;
             return "You owe ". $this->name. ' $'. $total. '.';
          }
       }
  8. Just like when we declared a function earlier, declaring a class doesn’t make anything happen until we instantiate an instance of that class. In order to create a new lawyer, we need to create a variable using the new keyword. Create a new Lawyer by adding the bold code:

    function get_bill($hours) {
          $total = $this->hourly_rate * $hours;
          return "You owe ". $this->name. ' $'. $total. '.';
       }
    }
    $alfred = new Lawyer();
  9. Let’s give our new lawyer a name and hourly rate:

    function get_bill($hours) {
          $total = $this->hourly_rate * $hours;
          return "You owe ". $this->name. ' $'. $total. '.';
       }
    }
    $alfred = new Lawyer();
    $alfred->name = 'Alfred Frank';
    $alfred->hourly_rate = 50;
  10. Call the results by adding:

    $alfred = new Lawyer();
    $alfred->name = 'Alfred Frank';
    $alfred->hourly_rate = 50;
    
    echo $alfred->get_bill(2);

    This is how we call a method on an object. First we create the new Lawyer ($alfred) and set up some properties for it. Then we call the get_bill method within the class and pass it an argument (the number of hours).

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

  12. Return to your code editor.

  13. One really powerful thing we can do is have multiple instances of the same class going at once, all with different properties. Add a new Lawyer preceded by a line break:

    $alfred = new Lawyer();
    $alfred->name = 'Alfred Frank';
    $alfred->hourly_rate = 50;
    
    echo $alfred->get_bill(2);
    
    echo '<br>';
    
    $juanita = new Lawyer();

    This creates a new instance of the Lawyer class, which can have completely different properties.

  14. Let’s add properties and get the bill for the new lawyer:

    echo '<br>';
    
    $juanita = new Lawyer();
    $juanita->name = 'Juanita Jones';
    $juanita->hourly_rate = 150;
    echo $juanita->get_bill(5);
  15. Save the file, go to the browser, and reload. You should see You owe Juanita Jones $750. Now we’re writing some really dynamic code! We’ve got two different objects with different properties, and our code is really efficient because it’s all running through the same functions and the same class.

  16. Return to your code editor.

Private Properties

So far we’ve only dealt with public properties, but we should also discuss private properties. Most classes in PHP source code use private properties, which as you might guess, are not as easily accessed as public properties.

  1. Around line 12, change public to private:

    private $name, $hourly_rate;
  2. Save the file, go to the browser, and reload. You will either see a blank page or an error, which says, Cannot access private property Lawyer::$name.

  3. Return to your code editor and around line 20, notice this is where we tried to set the Lawyer name.

    With public properties using the stdClass object, we could set a property by simply making it equal to something. With private properties, we’ll have to take a different approach. Usually private properties are set through methods. Commonly, important properties are set when an object is first created.

  4. It’ll help to clean up our code so we can start fresh. Delete lines 20–30, so that section of code looks like so:

    $alfred = new Lawyer();
    
    ?>
  5. Create a new function around line 14:

    class Lawyer {
       private $name, $hourly_rate;
    
       function __construct()
    
       function get_bill($hours) {

    Make sure you type two underscores (__) before construct. __construct is a special method for any class you create. This method is called whenever your class is initialized with that new keyword.

  6. Between the parentheses, you can accept arguments and use them to do things with your class. For example, setting private properties when a class instance is created. Add the bold code:

    function __construct($name, $hourly_rate)
  7. To set these properties permanently on the object, add:

    function __construct($name, $hourly_rate) {
       $this->name = $name;
       $this->hourly_rate = $hourly_rate;
    }
  8. Around line 24, add our new Lawyer’s name and hourly rate:

    $alfred = new Lawyer('Alfred Frank', 50);
    
    ?>

    Here, we are passing our new Lawyer’s name and hourly rate within that call to new Lawyer. Those two values will get sent to the __construct function and used to set up the Lawyer’s private properties.

  9. Let’s call the results for a bill of 10 hours. Add:

    $alfred = new Lawyer('Alfred Frank', 50);
       echo $alfred->get_bill(10);
    
    ?>
  10. Save the file, go to the browser, and reload. You should see You owe Alfred Frank $500. Great, things are working again!

Creating Classes That Extend Classes

New classes can be created to extend (or add additional functionality to) existing classes.

  1. In your code, delete lines 24–25 and replace them with the following bold code:

    class BillboardLawyer extends Lawyer {
       }
    
    ?>

    This tells PHP that this class is going to build on the Lawyer class. We don’t have to redefine anything that’s already there (for example, we don’t need to add a private name or hourly rate or redo the __construct function).

  2. We do however, want the get_bill function to work a little differently here. Add the bold code to start redefining the function:

    class BillboardLawyer extends Lawyer {
       function get_bill($hours) {
       }
    }
  3. Our goal is for the original bill to print along with some additional text. First, let’s make sure we get the original bill by typing:

    class BillboardLawyer extends Lawyer {
       function get_bill($hours) {
          $original = parent::get_bill($hours);
       }
    }

    This says to go to the parent class (Lawyer) and execute the function get_bill there using the value $hours.

  4. We want to return that original bill appended with a bit more text. Type:

    class BillboardLawyer extends Lawyer {
       function get_bill($hours) {
          $original = parent::get_bill($hours);
          return $original. ' And you pay NOTHING until we recover for YOU!';
       }
    }
  5. Now let’s make Alfred a billboard lawyer and get his bill for 20 hours. Type:

    class BillboardLawyer extends Lawyer {
       function get_bill($hours) {
          $original = parent::get_bill($hours);
          return $original. ' And you pay NOTHING until we recover for YOU!';
       }
    }
    
    $alfred = new BillboardLawyer('Alfred Frank', 500);
    echo $alfred->get_bill(20);
  6. Save the file, go to the browser, and reload. You should see You owe Alfred Frank $1,000. And you pay NOTHING until we recover for YOU!

In summary, we’re now using the same __construct method and private properties of the Lawyer class without having to do anything additional. Then we’re overriding the get_bill function, calling the original parent function, and appending text onto the output before returning it.

  1. Great! We’re done for now. Feel free to close your files.

Noble Desktop Publishing Team

The Noble Desktop Publishing Team includes writers, editors, instructors, and industry experts who collaborate to publish up-to-date content on today's top skills and software. From career guides to software tutorials to introductory video courses, Noble aims to produce relevant learning resources for people interested in coding, design, data, marketing, and other in-demand professions.

More articles by Noble Desktop Publishing Team

How to Learn Full-Stack Web Development

Master Full-stack Web Development with Hands-on Training. Build Fully Functional Websites and Applications Using HTML, CSS, JavaScript, Python, and Web Developer Tools.

Yelp Facebook LinkedIn YouTube Twitter Instagram