This tutorial will scratch the surface of object oriented programming in PHP. Object oriented programming or OOP, will help you create clean logic abstractions, saving you time from having to re-write code over and over again. Let’s get started!

Creating The Class Constructor

Before we create our object, we need to make a blueprint for what our object is going to contain. Create a new class file and name it Hello.php, open that class and type the following:

And that’s a very basic class, as you can see we have two methods in the class, world() and name(). Our method name() accepts one parameter and that’s the $name variable. If you’re familiar with PHP functions you will quickly recognize what these two functions do. The world function prints out “Hello World”, and the name function prints out “Hello” and the parameter string that is passed through at the time you call the method.

Create The Object

Now that we have our class (our object’s blueprint), we can move over to our index.php file and create our PHP object. Let’s begin by referencing our class file in the top of index.php with a require statement.

Now the class should be available to our current file and we’re ready to create the object:

In PHP, you initialize a new object by typing the keyword new and then the name of the class, followed by parenthesis. Now that we’ve got our object initialized, we can call our methods that were defined in Hello.php on our new object!

Remember, we can only call the world() and name() methods on our object because those were the only methods defined in our class, so let’s do that:

Awesome, let’s give that index.php a test run and see what happens in the browser:

As you can see, it’s much easier to create a class and initialize objects as opposed to using traditional functional programming. Object oriented programming is a widely accepted standard for creating applications with dynamic data and should be practiced accordingly.

Our whole index.php file: