Welcome to the first in a series of tutorials covering object-oriented programming in PHP. In this series you’ll explore the various ideas and concepts involved in object-oriented programming, and learn how to build robust object-oriented PHP applications quickly and easily.
In this tutorial, we’re going to kick things off nice and gently by looking at some really basic concepts of object-oriented programming. You’re going to learn:
- What object-oriented programming is
- How object-oriented programming can help you write better PHP scripts
- Some fundamental concepts, including classes, objects, methods and properties, and
- How to start writing object-oriented PHP code.
Ready to explore the world of PHP objects? Let’s get started!
What is object-oriented programming?
If you’ve ever created and used your own functions in PHP then you’ve been using a programming style known as procedural programming. With procedural programming, you typically create data structures — numbers, strings, arrays, and so on — to hold your data, then you pass those data structures to functions that operate on that data.
Object-oriented programming, or OOP, takes things further by storing both the data structures, and the functions that work on the data, in a single entity known as an object. Rather than passing data around in function calls, you instead load the data you want to work with into an object, then call the object’s functions to manipulate the object’s data and produce the result you want.
Often, the objects that you create with OOP tend to reflect real-world entities. For example, if you were writing a forum system for your website, you might create a Member
object that contains all the information about a given forum member (name, username, email address, password, and so on), as well as functions to operate on that data (register, login, logout, ban, and so on).
Why use object-oriented programming?
Procedural and object-oriented programming are two different ways to do the same thing. Neither style is “better” than the other — it’s largely down to personal preference — and you can freely mix and match procedural and object-oriented code in a single PHP script.
That said, there are some advantages that OOP can offer you as a developer:
- Easy to map onto real-world situations: As I mentioned earlier, objects can easily map onto real-world “objects” such as people, products, shopping carts, blog posts, and so on. This makes life easier when you set out to design your object-oriented applications, since the purpose of each object, as well as the relationship between objects, is already fairly clear.
- Easy to write modular code: OOP naturally lends itself to writing code in self-contained modules. By separating your code into distinct modules, you make your code more manageable, and easier to debug and extend.
- Easy to write reusable code: Writing reusable code can save you a great deal of time when writing an app, and over time you can build up a library of reusable code modules that you can use in many different apps. OOP makes it relatively easy to write reusable code, since data structures and functions are nicely encapsulated in a single, reusable object. It’s also possible to take an existing object and extend it to add new functionality for a specific application, which again makes objects easy to reuse.
Some fundamental concepts
Before we move onto writing object-oriented code in PHP, it’s important to understand 4 fundamental OOP concepts: classes, objects, properties, and methods.
Classes
A class is a blueprint for objects. It’s a chunk of code that defines:
- The types of data that objects created from the class will store, and
- The functions that those objects will contain.
When you build your object-oriented application, you typically create one or more classes representing various types of entities in your app. For example, if you’re writing a forum application, you might create classes called Forum
, Topic
, Post
, and Member
.
Objects
An object is a special type of variable that is created from a class. It contains actual data, and you can call the object’s functions to do stuff to that data. You can create as many objects as you like from a single class. Each object functions independently of the others, even if they all come from the same class.
To use a real-world analogy:
- A class is like a blueprint for a car. It defines how cars created from the blueprint will look and behave, but it’s still an abstract concept.
- An object is like a real car created from the blueprint. It has real properties (such as how fast it’s going), and real behaviours (like “accelerate” and “brake”).
An object is often said to be an instance of a class, and the process of creating an object from a class is called instantiation.
Properties
The data values that an object holds are stored in special variables known as properties. An object’s properties are closely tied to the object. Although all objects created from a given class have the same properties, one object’s properties can have different values to another object’s properties.
Methods
The functions that are defined within a class — and used in an object — are known as methods. In many ways, they’re just like regular functions — you can pass values to them, they can contain local variables, and they can return values. However, an object’s methods typically work mostly with the object’s properties. For example, a login()
method to log a member into your forums might set the member’s loggedIn
property to true.
How to create classes in PHP
Now that you know what classes, objects, properties and methods are, it’s time to get down to business and create some classes and objects using PHP code.
First, let’s look at creating a class. The basic syntax for creating a class in PHP looks like this:
class ClassName
{
// (class definition goes here)
}
For example, if you were creating a Member
class for a web forums application, you’d write:
class Member { // (class definition goes here) }
Pretty straightforward stuff! Of course, this class doesn’t do much until you’ve added properties and methods to the class. Nevertheless, the above code creates a valid, usable class in PHP.
It’s good programming practice to put each class’s code in its own file, with the same name as the class. For example, you might put the above Member
class code in a file called Member.php
, and store the file in a folder called classes
.
How to create objects in PHP
You create an object from a class by using the new
keyword, as follows:
new ClassName()
This creates an object based on the class ClassName
. Usually you’ll then want to store your newly-created object in a variable so that you can access it later. For example, let’s create a new Member
object and store it in a variable called $member
:
$member = new Member();
We can also create another object from the same class if we want:
$member2 = new Member();
Even though we created them from the same Member
class, $member
and $member2
are independent of each other.
Adding properties to a class
Now that we know how to create classes and objects, let’s look at adding properties. There are 3 types of property that you can add to a class:
- Public properties can be accessed — that is, read and/or changed — by any code in your script, whether that code is inside or outside the class.
- Private properties can only be accessed by methods within the class. It’s best to make your properties private if possible, since it helps to keep your objects separated from the rest of your code.
- Protected properties can be accessed by methods within the class, and also by code in classes that inherit from the class. (We’ll cover inheritance in a later tutorial.)
To add a property to a class, you write the keyword public
, private
or protected
, followed by the property’s name:
class ClassName
{
public $propertyName;
private $propertyName;
protected $propertyName;
}
Let’s add a public property to our Member
class to store the member’s username:
class Member { public $username = ""; }
Notice that we’ve also initialized our property with an empty string, ""
. This means that, when a new Member
object is created, $username
will be set to an empty string initially. As with regular variables, you don’t have to initialize properties, but it’s often a good idea. If you don’t initialize a property then it’s given a default value of null
.
Accessing properties
To access an object’s property you use the ->
operator, as follows:
$object->propertyName
Let’s try this out. We’ll create a script that declares our Member
class and property, creates a new Member
object, then sets and reads the object’s username
property:
<?php class Member { public $username = ""; } $member = new Member(); $member->username = "Fred"; echo $member->username; // Displays "Fred" ?>
If you run the above code then it will display “Fred”, the value of the $member->username
property. As you can see, you can treat an object’s property much like a regular variable — you can read its value, and you can assign new values to it.
Adding methods to a class
How about adding methods to a class? As I mentioned earlier, methods are simply functions that are part of a class. So it probably comes as no surprise that you create a method much like any other function — by using the function
keyword. The only difference is that you should also add public
, private
or protected
to the method definition, much as you do with properties:
class ClassName
{
public function methodName() {
// (Method's code here)
}
private function methodName() {
// (Method's code here)
}
protected function methodName() {
// (Method's code here)
}
}
As with properties, public methods can be called from anywhere, private methods can only be called by other methods in the class, and protected methods can be called by methods in the class and in any derived classes.
Let’s try adding some methods to our Member
class. We’ll add:
- A private property called
$loggedIn
to record whether the member is logged in or not - A method called
login()
that logs the member in by setting$loggedIn
totrue
- A method called
logout()
that logs the member out by setting$loggedIn
tofalse
- A method called
isLoggedIn()
that returns the value of$loggedIn
Here’s our script:
<?php class Member { public $username = ""; private $loggedIn = false; public function login() { $this->loggedIn = true; } public function logout() { $this->loggedIn = false; } public function isLoggedIn() { return $this->loggedIn; } } ?>
Notice that we’ve used a new keyword inside our methods: $this
. In the context of an object’s method, the special variable $this
refers to the object itself. By using $this
within an object’s method, the method can access any of the other properties and methods in the object.
For example, the login()
method accesses its object’s $loggedIn
property by using $this->loggedIn
.
By the way, we made our $loggedIn
property private so that outside code can only access it through the login()
, logout()
and isLoggedIn()
methods. This is a good approach, as it keeps the inner details of the object — such as how it records whether a member is logged in or out — separate from the outside code. Use private properties whenever possible to keep your objects self-contained, portable, and secure.
I made the $username
property public mainly to show how to access properties earlier in the tutorial. In a real-world app you’d probably want to make $username
private too, and add public methods to read and set the username if necessary.
Using methods
To call an object’s method, you use your old friend, the ->
operator:
$object->methodName()
This works just like a regular function call. You can pass arguments inside the parentheses (assuming the method can accept arguments), and the method call can also return a value that you can use.
Now that we’ve added some methods to our Member
class, let’s try using them:
<?php class Member { public $username = ""; private $loggedIn = false; public function login() { $this->loggedIn = true; } public function logout() { $this->loggedIn = false; } public function isLoggedIn() { return $this->loggedIn; } } $member = new Member(); $member->username = "Fred"; echo $member->username . " is " . ( $member->isLoggedIn() ? "logged in" : "logged out" ) . "<br>"; $member->login(); echo $member->username . " is " . ( $member->isLoggedIn() ? "logged in" : "logged out" ) . "<br>"; $member->logout(); echo $member->username . " is " . ( $member->isLoggedIn() ? "logged in" : "logged out" ) . "<br>"; ?>
The above script displays the following:
Fred is logged out Fred is logged in Fred is logged out
Here’s how the script works:
- After defining the
Member
class as before, we create a newMember
object and store its value in$member
. We also set the member’s username to “Fred”. - We then call
$member->isLoggedIn()
to determine if the member is currently logged in.isLoggedIn()
simply returns the value of the$loggedIn
property. Since$loggedIn
defaults tofalse
,isLoggedIn()
returnsfalse
to the calling code, resulting in the message “Fred is logged out”. - Next we call the
$member
object’slogin()
method. This sets the object’s$loggedIn
property totrue
. - Now, when we call
isLoggedIn()
again, it returnstrue
, so our code displays “Fred is logged in”. - We then call the
$member
object’slogout()
method, which sets the$loggedIn
property tofalse
. - Finally, we call
isLoggedIn()
a third time. This time it returnsfalse
, because$loggedIn
is set tofalse
again. This causes our code to display “Fred is logged out” once more.
In case you’re not familiar with it, the ?:
used in the example above is the ternary operator. It’s like a compact version of an if ... else
statement. Find out more in the PHP manual.
Summary
In this tutorial you’ve looked at the basics of object-oriented programming in PHP. You’ve explored the following topics:
- The nature of object-oriented programming, and why it’s useful
- The concepts of classes, objects, properties and methods
- How to create classes and objects in PHP
- How to create and use properties in PHP
- The concept of public, private, and protected properties and methods
- How to create and use methods in PHP
There’s a lot more to PHP object-oriented programming than we’ve covered here, and we’ll be exploring more OOP concepts and techniques in future tutorials. However, if you’ve worked through this tutorial then you now have a good understanding of the fundamental concepts of object-oriented programming in PHP. You’re now well on your way to writing object-oriented PHP applications and websites.
When you’re ready, try reading the next tutorial in the series: Object-Oriented PHP: Delving Deeper into Properties and Methods.
Happy coding!
GMCDesign says
This article couldn’t have come at a better time! Thank you!
matt says
@GMCDesign: Glad to hear it! I hope you found the article useful. 🙂
More OOP tutorials coming soon…!
underpaidmonkey says
Matt,
Absolutely loved the article although was confused by the statement “With procedural programming, you typically create data structures — numbers, strings, arrays, and so on — to hold your data”. When you say data structure, what are you referring to exactly? Are you referring to variables that hold the data e.g. $username = ‘Fred’ where the data Fred is a string?
Can’t wait for the next tutorial.
UM
matt says
@underpaidmonkey: Thanks for your comment!
“Data structure” is an abstract term that refers to the way that a particular item (or items) or data are stored. For example, numbers and arrays are both data structures. Numbers are typically stored in a single memory location, whereas arrays contain multiple items of data spread over several memory locations, indexed by keys. So these 2 data structures store their data in different ways.
If you had a variable called $myArray that held an associative array, then the variable would be $myArray and the data structure would be the array that holds the data.
Does that help?
“Can’t wait for the next tutorial”
Already published!
http://www.elated.com/articles/object-oriented-php-delving-deeper-into-properties-and-methods/
Cheers,
Matt
sambarino says
What an absolutely tremendous article! I’ve struggled to get my head around the basic concepts of OOP but this article is so well written with practical examples that I now understand 😀
Many thanks for sharing.
matt says
@sambarino: Thanks for the kind words – much appreciated 🙂
Matt
matbaa says
objective programming is really a very nice article was to understand the Thank you solve programming
matt says
@matbaa: You’re welcome!
syed says
Dear,
sir, as i see your tutorial for oops .it so nice . know i can say after read your tutorial . i can make login form in php with oops concept. but sir expand tutorial in same page for further reading.
thanks sir
syed says
sir,
Are you work on PHP only or else .net , java etc ?
thanks