There are lots of different ways to code in PHP. That's actually one of its strengths - you can start creating basic PHP pages with very little knowledge, but you can also take it further using more advanced, complex tools that are also more powerful and flexible. :)
Object-oriented programming, or OOP for short, is a well-known programming technique that's been around for years. PHP didn't invent it - languages like C#, C++, Java, and Python were using it long before PHP came into the picture.
Now, let's be clear: object-oriented programming isn't "magic." It won't suddenly make your website awesome overnight. But it will help you organize your code better, make it easier to expand later on, and let you reuse parts of your code to save time and make everything clearer. That's why professional developers rely on it in most of their projects.
This chapter, just like the one on regular expressions, is going to be split into two parts. Don't worry — OOP isn't nearly as scary as regex. :) It's just that one part is a bit more theoretical, the other is more hands-on, and it's easier to tackle them separately (plus, yeah, it's kinda long ^^).
What is an object in PHP?
I've said it before and I'll say it again: object-oriented programming won't revolutionize your website overnight, despite what you might've heard. In fact, at first it might even feel a bit pointless. You might find yourself thinking, "Okay, but what's the point? Everything worked just fine before." Some parts will probably seem a little abstract too — you might not immediately see how this stuff applies to your own site. That's totally normal. When learning OOP, there's a bit of a transition period where the link between theory and practice isn't always clear.
Still, take the time to read through everything and try to really understand what's being explained. With a bit of practice, you'll see how this gives you more control over your PHP code as your site grows, and eventually you'll realize just how valuable this all is. ;)
Fresh and shiny objects
Let's start by defining what we actually mean by an "object" in programming. So, what is it?
Exactly — that's a great starting point. :)
We are, in fact, surrounded by objects. Pretty much everything we know can be thought of as an object. The idea behind object-oriented programming is to work with elements called "objects" inside your code.
Neither, actually. It's something new. To be more specific, an object is... a mix of several variables and functions. o_O
Don't panic — you'll get the hang of it soon enough. ;)
Picture an object
To keep this from sounding like some abstract modern art theory, let's use a few down-to-earth examples to get a clearer idea of what an object really is.
Imagine a developer decides to build a members area for their website — something that lets them add users, assign them to groups (admin, moderator, etc.), ban them, delete them... The code quickly gets complex. They have to create lots of functions that call one another, and use variables to store the member's name, signup date, group, and so on.
It takes time and effort to build, it's kind of messy, but eventually it works. The final code is made up of various functions and variables. At first glance, it looks like some mad scientist's experiment that no one else can understand.
Now, this developer is proud of their work and wants to share the code online, so others can easily set up a members section on their own sites without reinventing the wheel. But here's the problem: unless you have a degree in chemistry, you're going to spend a lot of time trying to figure out how all this stuff works.
Which function do you call first? What values do you pass to which function to create a new user?
This is where our friendly developer has a lightbulb moment. They decide to rewrite their code using object-oriented programming. That means they take their whole chemistry lab and pack it neatly into a single cube. That cube is what we call an object.
Of course, this is just a metaphor — but it's the key idea to understand and remember for now. ;)
Classes and objects in action
You've already used objects before!
Yup! Remember PDO? Don't tell me you've already forgotten. ;)
PDO is a PHP extension, and it's written in object-oriented style. That's why it looked and behaved a bit differently from the regular functions we'd been using up to that point.
I promised I'd explain PDO in more detail, and now's the perfect time! Remember this line we used to connect to a database?
<?php $db = new PDO('mysql:host=localhost;dbname=test', 'root', '', $pdo_options); ?>
$db isn't just a variable — it's actually an object. You create an object in PHP using the new keyword followed by the class name.
- A class is a blueprint or template for an object. Think of it like an architectural plan for building a house.
- An object is an instance of a class — it's the actual house built from that blueprint. You can use the same plan to build many houses, just like you can create multiple objects from a single class.
Class -> Object 1 Class -> Object 2 Class -> Object 3
So, going back to our example, you've probably figured out:
- $db is the object
- PDO is the name of the class the object is based on
As I mentioned earlier, an object is a combination of functions and variables. When you use it, you call its functions like this:
<?php $db->query(); $db->prepare(); $db->execute(); ?>
This means: run the query() function from the $db object, then prepare(), then execute(), and so on. The ->
arrow is specific to objects. So what we're really doing is calling functions on the $db object, which represents our database connection.
Here's another (imaginary) example, just to make sure the idea's crystal clear:
<?php $house1 = new House(); $house2 = new House(); $house1->clean(); ?>
In this case, we have two objects representing houses ($house1 and $house2), but we're only calling the clean() function on house 1 — so it's the only one that'll be tidy. ;)
One of the big advantages of object-oriented programming, as you can see, is how readable the code becomes. It's clean and easy to understand.
Next up in this chapter, we'll learn how to create our very own classes.
Creating a Class
For our examples, we're going to imagine we're building a Member class to represent a member of our site. We'll be able to load a member using their info from the database, get their username, registration date, ban them, log them out, and more.
Since class code tends to be a bit long, it's a good idea to create a separate PHP file just for the class definition, and include it whenever needed. I suggest naming the file Member.class.php
.
.class.php
extension for files that define classes, to make things clearer. A few rules here: only define one class per file, and name the file after the class. Also, class names usually start with an uppercase letter.Inside your Member.class.php
file, start with the following:
<?php class Member {} ?>
?>
tag. It might seem strange, but doing so helps avoid inserting blank lines at the end of the PHP code — which can trigger annoying bugs like "Headers already sent by..."Inside the curly braces, we'll define variables and functions that belong to the class.
Quick vocab note: developers often use other names for these class members. Here's a breakdown:
- Member variables are also called attributes or properties
- Member functions are also known as methods
Let's try adding some variables and functions to our Member class.
Member Variables
Variables define what makes an object unique. So what defines a member? Let's try listing a few of their attributes (if we forget some, no big deal — we can always add them later). A member has:
- A username
- An email
- A signature
- A status (active or not, depending on whether their account is validated or banned)
We'll store all this info as text variables. Add them like this:
<?php class Member { private $username; private $email; private $signature; private $active; } ?>
We're saying that our Member class includes four variables: $username, $email, $signature, and $active. Right now, they don't have any values.
Don't worry yet about the private keyword — I'll explain what that means in a bit. 😉
Member Functions
Now that we've got our variables, let's add some functions. Their purpose will be:
- To read or update those variables. These are called getters and setters
- Or to perform more complex actions on the member (like sending them an email)
Getters and Setters
These are functions that start with get or set, depending on whether we want to retrieve a value or change it.
Let's take the username as an example. We'll create a getUsername() function that returns the username, and a setUsername() function that updates it.
<?php class Member { private $username; private $email; private $signature; private $active; public function getUsername() { return $this->username; } public function setUsername($newUsername) { $this->username = $newUsername; } } ?>
So we now have two simple functions for working with the member's username. As you can see, they're pretty straightforward.
getUsername() just returns the username:
public function getUsername() { return $this->username; }
The $username variable is accessed inside the function using $this->
. That means "the username of this object". Remember, we can create multiple objects from a single class — there could be lots of members, each with a different username.
The $this-> prefix makes it clear we're working with the specific member at hand.
Similarly, setUsername() takes a new value and assigns it to $this->username
.
Actually, even if getters and setters seem simple, they're really powerful. They let us add logic when changing a variable.
Let's improve setUsername() with some validation:
public function setUsername($newUsername) { // Make sure the new username isn't empty or too long if (!empty($newUsername) && strlen($newUsername) < 15) { // Looks good, update the username $this->username = $newUsername; } }
Now the username will only be updated if it meets certain criteria: not empty and under 15 characters. You could also use this function to check for illegal characters or other rules.
The point of going through a function to update variables is that it gives you control. For example, when updating an email, you could check that the new value actually looks like a real email address.
Other Functions
Of course, we can add other kinds of functions to our Member class — not just ones that update variables. It's up to us to decide what kind of actions we want to perform: banning the member, sending them an email...
<?php class Member { public function sendEmail($subject, $message) { mail($this->email, $subject, $message); } public function ban() { $this->active = false; $this->sendEmail('You haves been banned', 'Don\'t come back!'); } ... } ?>
The sendEmail() function is simple: it uses PHP's built-in mail() function and the member's stored email address ($this->email
).
Meanwhile, the ban() function updates the member's status to mark them as inactive, then sends them an email letting them know they've been banned.
And notice: we're reusing our sendEmail() method. Just like with variables, we use $this->
to refer to a method from within the class.
That's the spirit of object-oriented programming: reuse your code instead of reinventing the wheel every time. 😊
Building an Object from a Class
At this point, you should have a file named Member.class.php
containing your class definition — that is, the blueprint for building your future objects:
<?php class Member { private $username; private $email; private $signature; private $active;public function sendEmail($subject, $message) { mail($this->email, $subject, $message); }
public function ban() { $this->active = false; $this->sendEmail('You have been banned', 'Don\'t come back!'); }
public function getUsername() { return $this->username; }
public function setUsername($newUsername) { if (!empty($newUsername) && strlen($newUsername) < 15) { $this->username = $newUsername; } } } ?>
Now that our class is ready (even if there's still room for improvement), we can start using it — that is, we can begin creating objects from it. Create a new file (name it whatever you want, for example index.php
) where you'll create and use an object of type Member.
<?phpinclude_once('Member.class.php');
$member = new Member(); $member->setUsername('Phil'); echo 'Watch out ' . $member->getUsername() . ', I\'m about to ban you!'; $member->ban();
?>
We begin by including the definition of the Member class from the Member.class.php
file. We use include_once() to make sure the file hasn't already been included somewhere else on the page — which would trigger an error, since defining the same class twice is a no-go.
Next, we create a new Member object with the line:
$member = new Member();
We now have a $member object that represents a blank member. We set a username, display it, and — just for fun — ban the poor guy. :-°
This gives you a concrete example of how to use a class. Even though it's pretty basic, you could already hand off your Member.class.php
file to fellow coders (ideally with a bit of documentation explaining how to use it), and they'd be able to create and manage members just like you did.
A class is kind of like a plug-and-play package. It comes with its own set of variables and functions. To use it, all we have to do is call those functions, without worrying about what's going on inside. This ties back to the model I showed you at the start of this chapter.
The variables and the function code inside the class aren't really the concern of the programmer using it. They just press buttons — so to speak — calling whatever functions they need to work with their member: "Give him the username Matt," "Ban him," and so on.
I've done my best in this introductory chapter on OOP in PHP to keep things as hands-on as possible, but trust me — it's by practicing that it'll all start to click. See you in the next chapter for that! 🙂
Enjoyed this PHP & MySQL course?
If you liked this lesson, you can find the book "How to Build a Website in HTML and CSS" from the same authors, available on SiteRaw, in bookstores and in online libraries in either digital or paperback format. You will find a complete PHP & MySQL workshop with many exclusive bonus chapters.