Dive into this comprehensive tutorial on PHP & MySQL, where you'll find topics like functions, arguments, objects & properties, creating classes that extend other classes, and more. The content is perfect for anyone looking to broaden their knowledge of PHP & MySQL, whether you're a beginner or a seasoned programmer.
Key Insights
- Functions in PHP are code routines that can be called at any time and can be defined with the word "function" followed by the function name and parentheses.
- Arguments in functions are outside values that are sent into a function when it’s called. They can vary each time a function is called and add flexibility to your code.
- PHP objects can contain methods, which are functions inside of a class. Using methods within a class can make objects very powerful.
- Private properties in PHP are not as easily accessed as public properties. Most classes in PHP source code use private properties.
- Functions become more useful when arguments are passed in. Arguments can vary each time a function is called, adding more flexibility to your code.
- New classes can be created to extend (or add additional functionality to) existing classes. This is a powerful tool for code reuse and efficiency.
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.
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 ?>
-
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.
-
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.
-
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. -
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.
Switch back to your code editor.
-
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. Save the page, then go back to the browser and reload objects.php. Now you should see the value 300.
Return to your code editor.
-
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.
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.
-
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; }
-
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; }
-
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>';
-
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);
Save the file, then go back to the browser and reload objects.php.
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.
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.
-
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; }
-
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);
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.
-
In your code editor, delete the entire function so that you’re left with empty PHP tags:
<?php ?>
-
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 calledlawyer
. 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. -
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 thatname
is a property of ourlawyer
object. -
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.
-
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.
-
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. 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.
Go back to your code editor.
-
Delete all the
lawyer
object code so that you’re again left with empty PHP tags:<?php ?>
-
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. -
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). -
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 theLawyer
object, so it’s already known to us within the function, which is why we didn’t need to specify it as an argument. -
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 theLawyer
object from within theLawyer
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 theLawyer
class.$this->hourly_rate
gets the hourly rate of this specific lawyer. -
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. '.'; } }
-
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();
-
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;
-
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 theget_bill
method within the class and pass it an argument (the number of hours). Save the file, go to the browser, and reload objects.php. You should see You owe Alfred Frank $100.
Return to your code editor.
-
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.
-
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);
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.
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.
-
Around line 12, change public to private:
private $name, $hourly_rate;
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.
-
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.
-
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(); ?>
-
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 (
__
) beforeconstruct
.__construct
is a special method for any class you create. This method is called whenever your class is initialized with that new keyword. -
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)
-
To set these properties permanently on the object, add:
function __construct($name, $hourly_rate) { $this->name = $name; $this->hourly_rate = $hourly_rate; }
-
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. -
Let’s call the results for a bill of 10 hours. Add:
$alfred = new Lawyer('Alfred Frank', 50); echo $alfred->get_bill(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.
-
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). -
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) { } }
-
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 functionget_bill
there using the value$hours
. -
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!'; } }
-
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);
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.
- Great! We’re done for now. Feel free to close your files.