- PHP OOP Classes & Objects Tutorial
- Object Oriented Programming
- What is a class?
- Class attributes
- How to create a class
- How to instantiate a class (create an object)
- How to access data in a class object
- How to modify attribute values in a class object
- How to refer to class members without instantiating an object (::)
- How to access a constant in a class with the double colon (::)
- Multiple instances of a class
- Summary: Points to remember
- PHP OOP — Classes and Objects
- OOP Case
- Define a Class
- Syntax
- Define Objects
- Example
- Example
- PHP — The $this Keyword
- Example
- Example
- Example
- PHP — instanceof
PHP OOP Classes & Objects Tutorial
In this tutorial we learn how to further encapsulate our application’s data and behavior into larger, reusable units with classes and instance objects in PHP.
Object Oriented Programming is a notoriously difficult topic for new programmers to understand. It can be tough because of the shift in how we structure our code and how we think about writing our programs.
This section of the tutorial course may take you longer to understand than the others.
Object Oriented Programming
Object Oriented Programming, or OOP for short, is a way to treat data and behavior as single, reusable units. We try to model our application after entities in the real world by encapsulating data and behavior into classes.
So far we’ve learned to wrap our data and program behavior into reusable units called functions.
"""In the example above, we define some functions that we reuse for each user that wants an alert.
What if we could take all these functions and wrap them together inside another, bigger, unit that we can also easily reuse. That’s essentially what classes allow us to do, among many other things. Where it becomes confusing for new developers is the way that we do it.
Before we go any further, let’s wrap the example above into a class so we can see what it would look like. Don’t worry too much about understanding the code at the moment.
"""If we run the example above, it will do exactly the same as the previous example where the code wasn’t in the class.
You might be wondering why anyone would do this, it just seems like extra steps to accomplish the same thing. Object oriented programming has many advantages over procedural programming, such as maintainability, scalability, reusability etc.
For the moment we won’t worry about that, and instead focus on understanding the concept and implementation of classes and objects.
If we look closer at the examples, we can see an important difference between them. In the class, we no longer have any parameters in the functions. The values are taken from the variables at the top of the class and used directly inside the functions.
Because the functions and variables are inside the same class, the functions have access to the variables directly.
Another important difference is that the functions aren’t called directly, we access them through objects.
$user1 is an object, or instance, of the Alert class. Once we’ve defined an object, the object can use the functions inside the class.
What is a class?
A class is like a recipe, or blueprint, for an object. A class will define everything that an instance of it should contain.
Think of a class as a cookie cutter. It has a predefined shape that creates many cookies with the same shape. Some of those cookies might have icing and some might have chocolate chips, but they will all be the same shape.
If the class is the cookie cutter, the cookies are the objects. As an example, let’s consider a pizza.
This is our basic recipe (class) that can be used to make a pizza (object). When a baker makes a pizza, they create an object from the recipe.
Each pizza object that’s created will have a base, a sauce, toppings and cheese. The class doesn’t specify which toppings to use, only that some toppings can be used. It’s up to the programmer to decide what they want as ingredients.
The programmer will be able to create many types of pizzas by using only one class and changing individual ingredients.
Class attributes
A class attribute is a variable that is defined within a class. Other than a slightly different definition, it’s the same as any other variable.
They are called attributes instead of variables because we’re trying to model our application after entities in the real world. As an example, let’s consider a database of users.
Every user has attributes like:
- A name
- An age
- An address
- A profile picture
- An email
- A password etc.
Inside our class, normal variables will hold this data. Attributes are simply variables inside a class.
When defining an attribute, we must use the var keyword in front of the variable name.
A class method is a function that is defined within a class and is, again, the same as any other function. As an example, let’s consider our database of users.
Every user has functionality available to them, like:
Methods are simply functions inside a class.
When defining a method, we still use the function keyword in front of the method name.
The attributes and methods inside a class are known as its members.
How to create a class
A class is created almost like a function, except that there are no parameters in its definition because attributes and methods inside a class are accessed differently.
We write the keyword class , followed by the name of the class, and open and close curly braces to define the scope of the class.
In the example above we have a single attribute called $name, notice the var keyword in front of the name. Other than the var keyword, the attribute is exactly the same as any other variable.
We should be aware of two conventions typically used when naming classes:
- We name our classes in the singular. Instead of a class named Cars, we call it Car.
- We use Pascal casing. The first letter of the name is uppercase and each new word in the name has its first letter in uppercase. We don’t separate words with underscores.
We don’t have to name our classes this way but it is a good convention to follow. Some employers may require you to follow conventions such as these, or their own. In this tutorial series we will be using this convention.
How to instantiate a class (create an object)
Now that we have our cookie cutter (the class), we can create objects (cookies) from it. This is known as instantiating a class object.
We create a new object by using the new keyword when assigning the class to a variable.
Similar to a function, we write open and close parentheses after the class name when instantiating an object.
PHP allows us to provide parameters for class constructors between the parentheses, which we will look at a bit later on.
In the example above, we create a new object called $person1 from the Person class. The $person1 object will now have access to the $name attribute and the walk() method.
How to access data in a class object
When an object is instantiated, it receives all the attributes and methods that the class has. We access these attributes and methods with the arrow (->) operator.
We first write the object name, followed by the -> operator and then the attribute or method that we want to access.
When accessing an attribute we do not write the $ symbol in front of the attribute name.
When we run the example above, it will print out the $name attribute of the $person1 object. We also call the walk() method which will print the text “Walking…”
How to modify attribute values in a class object
When we want to modify the value of an attribute, we simply assign a new value to it.
Example: modify attribute values
When we run the example above, the $name attribute of the $person1 object is changed to “John”.
When we change the value of an attribute, the change is local, which means that only the $person1 object is affected. The Person class and any other objects will not be affected by the change.
How to refer to class members without instantiating an object (::)
Often, we want to refer to data in a class without creating an object for it first.
To do this, we have to use the scope resolution operator, more commonly known as the double colon (::), instead of the arrow (->).
Example: access class member with double colon
In the example above, we access the walk() method without instantiating an object first.
If we were to try and use the arrow to access the method directly, PHP would raise a Parse Error.
Parse error: syntax error, unexpected '->' (T_OBJECT_OPERATOR), expecting ',' or ';' in C:\xampp\htdocs\PHPProjects\main.php on line 13
How to access a constant in a class with the double colon (::)
If our class variable is a constant, we must access it with a scope resolution operator.
Remember, when defining a constant, we do not use the $ symbol as a prefix.
In the example above, we access the constant name with a double colon in both access cases.
If we were to replace the double colon with the arrow operator, the interpreter would raise an error.
Notice: Undefined property: Person::$name in C:\xampp\htdocs\PHPProjects\main.php on line 15
Because the constant isn’t accessed with the correct operator, the interpreter doesn’t recognize it and raises the error.
Multiple instances of a class
The whole purpose of a class is to use it to create many different instances of it.
To create another instance object of the class we simply instantiate the class into another variable.
When we run the example above, it will create a second instance of the class called $person2. We can have as many of these instances as we want.
Summary: Points to remember
- A class defines everything that an instance object of will contain. A class can be thought of as a cookie cutter, and objects as the cookies.
- An attribute is a data container such as a variable, or array. An attribute is available to the class scope and is defined, or instantiated, with the var keyword.
- A method is a function inside a class that is available to its scope. A method is still defined with the function keyword.
- An object is instantiated from a class by using the new keyword.
- Class members (attributes and methods) can be accessed through the object with the -> operator. And, when accessing members, we do not use the $ symbol as a prefix.
- When accessing a class member directly, without instantiating an object, we use the scope resolution operator (double colon — ::).
- Class members defined as const or static must be accessed with the scope resolution operator.
PHP OOP — Classes and Objects
A class is a template for objects, and an object is an instance of class.
OOP Case
Let’s assume we have a class named Fruit. A Fruit can have properties like name, color, weight, etc. We can define variables like $name, $color, and $weight to hold the values of these properties.
When the individual objects (apple, banana, etc.) are created, they inherit all the properties and behaviors from the class, but each object will have different values for the properties.
Define a Class
A class is defined by using the class keyword, followed by the name of the class and a pair of curly braces (<>). All its properties and methods go inside the braces:
Syntax
Below we declare a class named Fruit consisting of two properties ($name and $color) and two methods set_name() and get_name() for setting and getting the $name property:
class Fruit // Properties
public $name;
public $color;
?php
// Methods
function set_name($name) $this->name = $name;
>
function get_name() return $this->name;
>
>
?>
Note: In a class, variables are called properties and functions are called methods!
Define Objects
Classes are nothing without objects! We can create multiple objects from a class. Each object has all the properties and methods defined in the class, but they will have different property values.
Objects of a class are created using the new keyword.
In the example below, $apple and $banana are instances of the class Fruit:
Example
class Fruit // Properties
public $name;
public $color;
?php
// Methods
function set_name($name) $this->name = $name;
>
function get_name() return $this->name;
>
>
$apple = new Fruit();
$banana = new Fruit();
$apple->set_name(‘Apple’);
$banana->set_name(‘Banana’);
echo $apple->get_name();
echo «
«;
echo $banana->get_name();
?>
In the example below, we add two more methods to class Fruit, for setting and getting the $color property:
Example
class Fruit // Properties
public $name;
public $color;
?php
// Methods
function set_name($name) $this->name = $name;
>
function get_name() return $this->name;
>
function set_color($color) $this->color = $color;
>
function get_color() return $this->color;
>
>
$apple = new Fruit();
$apple->set_name(‘Apple’);
$apple->set_color(‘Red’);
echo «Name: » . $apple->get_name();
echo «
«;
echo «Color: » . $apple->get_color();
?>
PHP — The $this Keyword
The $this keyword refers to the current object, and is only available inside methods.
Look at the following example:
Example
So, where can we change the value of the $name property? There are two ways:
1. Inside the class (by adding a set_name() method and use $this):
Example
class Fruit public $name;
function set_name($name) $this->name = $name;
>
>
$apple = new Fruit();
$apple->set_name(«Apple»);
?php
2. Outside the class (by directly changing the property value):
Example
class Fruit public $name;
>
$apple = new Fruit();
$apple->name = «Apple»;
?php
PHP — instanceof
You can use the instanceof keyword to check if an object belongs to a specific class: