Lesson 2 - First object-oriented application in PHP

PHP OOP First object-oriented application in PHP

In the previous lesson, Introduction to object-oriented programming in PHP, we explained the whys and hows of OOP and took a quick peek at some actual OOP code. Today, we will be going deeper into detail of how OOP works and create our very first object-oriented application in PHP.

How OOP works

OOP's main purpose is to simulate reality as we perceive it. In other words, we no longer have to care how the program is seen by the computer, instead, we focus on our own perspective. They replaced the assembler with human readable mathematical notation and then that was replaced with OOP. Meaning that there is a certain level of abstraction above the program when OOP is put into use. This has significant advantages because it appears to be more natural and clear to us.

A unit in OOP is referred to as an object which may very well emulate an object in the real world (e.g. human or database objects).

Objects in object-oriented programming in PHP

Each object has its own attributes and methods.

Attributes

Object attributes are properties, or perhaps data that it stores. For example, a human's name and age, or a database's password. They are simply variables, with which we have worked hundreds of times. Occasionally they are referred to as the object's internal state. Attributes are bound to objects, which is how they differ from local variables (the kind of variable that we've been using up until now).

Methods

Methods are abilities that the object can perform. Humans, for example could have GoToWork(), Greet() or Blink() methods. Whereas for databases, AddEntry() or Search() would be more suitable. Methods can have parameters and may also return a value. Methods are bound to the object, which is how they differ from functions, which are global and a major problem of non-OOP code.

Class attributes and methods in object-oriented programming in PHP

PHP language started out with a procedural approach and later became object-oriented. In other words, we are able to program in an object-oriented way, but most of the functions provided by PHP are not object-oriented. The main reason being that PHP was created in a time when OOP was not as common as it is now. However, the situation gets better and better with every release. Through looking around and good old experience, you'll get to see just how awful larger projects look without OOP.

PHP has thousands of functions that aren't bound to objects. There as so many of them that no one gives them maintenance anymore. For example, most array functions start with the "array_" prefix (like array_reverse()), but the function to sort an array does not: sort(). If these functions were attributed to the array object, these problems wouldn't exist and one wouldn't have to spend as much time reading the documentation. The same goes for constants. Fortunately, the people who develop PHP are starting to realize that objects are absolutely necessary. Thanks to this realization, PHP now features objects for working with dates, databases and so on.

Classes

We have already encountered the term "class" before, I defined it as something along the lines of a set of commands. Classes, however, allow us to do so much more. A class is a pattern, based on which we create objects. In other words, it is an extensible program-template used to define properties and abilities.

An object that is created using a class is called an instance. Instances have the same interface as the class used to create them, but mutually differ in their internal data (attributes). For example, imagine that we have a Human class from which we create Carl and Jack instances. Both instances certainly have the same attributes (e.g. $name and $age) and methods (goToWork() and greet()) as the main class, but the values within them are different. For example, the first instance's name attribute has a value of "Carl" and an age of 22. Whereas the same attributes in the second one have "Jack" and 45 as values.

Class vs. instance in PHP

Communication between objects is performed via messages. A message looks something like this: $receiver->methodName(pa­rameters). In our case, it would be something along the lines of $carl->Greet(neighbor), which would make the Carl instance greet its neighbor instance.

PHP and objects

PHP began to support objects in version 4, but their implementation was such a disaster that nobody would use them. They gave it another shot in version 5, where implementation was inspired by the, very successful, object-oriented language - Java. Since version 5, object-oriented programming in PHP works rather well and once version 5.3 was released, PHP became a solid object-oriented language. This course is written for versions 5.3 and later. However, PHP 5.3 is a bit old, and we won't get into older versions since they would only run on low-quality hosting services. There is no point in learning older syntax that will eventually be deprecated, so we will work with objects using the latest versions of PHP.

First object-oriented application

Creating a class

Now let's get to the fun stuff and make our very first object-oriented application! We will stick to simple classes, for now. Mainly because demonstrating the theoretical aspects of what is going on within the program will be much easier for you to understand. In this course, you will see how objects in web applications differ from the ones used in system apps. However, there is a time for everything, and now is the time to keep things nice and simple.

Let's declare a Human class, which will allow us to create human instances.

We write classes in separate files, which are named after the class. Class names are written in CamelCase. Meaning that the first letter in every word in the class name must be written in upper-case. Keeping classes in a single folder will prove to be very useful to you. Now, let's create a "classes" folder and create a Human.php file there. Due to the fact that most servers run Linux, filenames are case-sensitive - so human.php won't work.

The file contents will be the following:

<?php
class Human
{


}

We declare classes using the "class" keyword and create a block using curly brackets (where we will declare its attributes). As you may have noticed, we opened a PHP directive at the beginning of the file and didn't close it. Doing so is a recommended practice. Since we know that there won't be any HTML in the file, the PHP directive should be left open so that it applies up until the end of the file.

Methods

We want our people to be able to do things. We'll start out simple and teach them how to greet. For now, all they'll do is print out, "Hi". Let's add a greet() method into the class:

<?php
class Human
{

        public function greet()
        {
                echo('Hi');
        }

}

As you can see, a method is rather similar to a function. The main difference is that it has what we refer to as a public access modifier. That means we will be able to call this method on the instance from outside of the class.

Now let's go back to our project folder and create an index.php file. To load the class, we'll have to use the require() function in order to create an instance of the class. However, to keep things safe, we will use the require_once() function, which will only load a class if it hasn't already been loaded prior to the function being called. Then, we create a Human class instance and make it greet us.

require_once('classes/Human.php');

$carl = new Human();
$carl->greet();

<?php

class Human
{

        public function greet()
        {
                echo('Hi');
        }

}

We store instances into variables. The variable names should be chosen carefully based on the variable content. We create instances using the "new" keyword, followed by the class name and parentheses. You can leave the parentheses out, but using them helps keep things readable (since we all know that methods often require parameters). We are now able to call the methods defined in the class using the instance we just created. We call methods using the arrow operator, which is technically a better way of calling functions.

Program output will be the following:

Your page
localhost

You can try running codes in our online compilers as well. All classes are there in a single file to keep it more readable on the website, however, you should always have classes as single files. Also, don't forget to open the PHP directive on the beginning of the class file.

Our application now works with objects. We could simply replace the entire thing with: echo 'Hi', however, more complex objects are almost irreplaceable due to their otherwise complex internal structures. Even when there is lots of code, things will stay clear and concise. In the next lesson, Attributes and magic methods in PHP, we will focus on object attributes and what we call "magic methods".

The code worked on today is available for download in the attachment below.


 

Download

Downloaded 46x (1.4 kB)
Application includes source codes in language PHP

 

 

Article has been written for you by David Capka
Avatar
Do you like this article?
1 votes
The author is a programmer, who likes web technologies and being the lead/chief article writer at ICT.social. He shares his knowledge with the community and is always looking to improve. He believes that anyone can do what they set their mind to.
Unicorn College The author learned IT at the Unicorn College - a prestigious college providing education on IT and economics.
Activities (13)

 

 

Comments

To maintain the quality of discussion, we only allow registered members to comment. Sign in. If you're new, Sign up, it's free.

No one has commented yet - be the first!