Introduction to Classes in PHP

Written on
October
13th,
2017
by
Karl Hughes

Like most object-oriented programming languages, classes are the backbone of PHP
projects. Classes allow you to group code into logical pieces, reuse code, and
prevent misuse of functions and variables.

This post will focus on the mechanics of classes and not the underlying concepts
in object oriented software design. If you are interested in the broader
question of “What is a class?” then check out the resources section below. If
you’re ready to learn how to apply object oriented programming to PHP, then read
on!

Creating a class

First, let’s see what it takes to create a class in PHP. Create a new file
called ExampleClass.php and add this code to it:

First, we named the file and class the same thing intentionally. While you don’t
have to follow all the PSR coding standards, PHP has pretty much adopted PSR-1 for most modern projects, so I’d
strongly recommend it.

Next, we can see that this class has one variable (public $variable;) and one
method (public function classFunction()…). Both use the visibility public
which will be explained in more detail at the end of this post, but for now,
just know that public variables and methods can be used and modified by other
classes.

Instantiating a class and calling a method

In order to use a class it typically has to be “instantiated” which is a
programming term meaning that we need to make a new object from the class. In
order to instantiate this class, let’s create a new file called index.php and
add this code:

But the problem is that as code bases get larger, new developers work with the
code, or we decide to release the code publicly, we need a better way to
organize our code and ensure that developers don’t misuse certain functions.
That’s where PHP’s class member
visibility helps us out.

Private member visibility

In order to keep certain elements in a class (called “members”) from being used
by code outside the class, you can mark a method or variable private . Here’s
an example modifying our ExampleClass above: