

The Complete Guide to Object-Oriented Programming With PHP (Part 1)
source link: https://www.tuicool.com/articles/hit/bqaEj2I
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Introduction
Learning object-oriented-programming is one if not the most valuable skills a web developer can learn .
For instance, there are places, like London, that are so competitive that you must have OOP among your abilities in order to get a job as a PHP Developer.
It is a very big step forward to understand and being able to apply the principles but the amount of reward later in your career is going to be huge.
Not to mention the enhancement of the quality of the code you will write and the time you are going to save by learning all these little tricks below.
Stay with me for one of the most important learning journeys of your life.
Differences Between Procedural and OOP
If you came across this article, you are probably interested in learning about object-oriented-programming, also called OOP.
In order to do that, we will have to take a step back and understand the programming paradigms and the main differences among them.
Until now, you probably have coded in what’s called procedural programming .
You write your PHP at the beginning of the page, connecting it with your database of choice, and creating variables to use just below in the same page, or maybe create all your PHP code in a single page and then require or include the script in your main page.
It is fine to work in this way. If you need to build something very small this could actually be a good idea because this paradigm creates less verbose code that in OOP, but there are several problems with this approach that will show up in the long run.
To begin with, in this way, the possibility to reuse the code is very limited if not impossible.
If you need to use the same block of code you need to rewrite it again somewhere else, if you need to update a functionality you will eventually need to edit all the blocks, and if you forget a block this will lead to problems and errors that will be really difficult to spot later on.
Not to mention this way makes the code bumbling, thus, very stressful for the eyes to work with, decreasing your focus and lowering the quality of the project.
More bad news for the practitioner of procedural programming is employment and job prospects in general. There are few jobs available for web developers who do not know object-oriented programming, In all honesty, depending on where you live, there will be no jobs if you do not know and understand the basics of MVC and how frameworks work as well.
To solve this problem, read a series of articles I have written aboutPHP frameworks.
On the other hand, OOP concepts solve these problems while adding new features that provide a modular structure to your project and make it very easy to maintain the existing code, which results in much more flexibility, just by using objects and classes.
What Is an Object?
As you might already know, in PHP, and the vast majority of programming languages, all data has its own type. In PHP, the types are:
- NULL
- Booleans
- Integers
- Floating point numbers
- Strings
- Arrays
- Resources
- Callbacks
- Objects
In this article, we will focus on the last type in the list: Objects.
According to Wikipedia “ An object refers to a particular instance of a class, where the object can be a combination of variables, functions, and data structures. ”
Clear right? Not really.
Think of an object like a building. A building has several characteristics (in programming they are called properties) such as windows, doors, rooms, and walls.
In PHP, you create an object using the new
keyword. Here is an example:
$myHome = new Building();
Now the variable $myHome
contains all the info included in a building.
Don’t worry if this is not clear yet.
In the following sections, we are going to explore the world of OOP using numerous examples.
These examples will supply you with a clear way to understand the concepts in this paradigm and make you ready to write objects, classes, and relationship by yourself.
Classes in PHP
What Is a Class?
I have already briefly mentioned what an object is and the concept of objects and classes are very similar, which could lead in quite a bit of confusion,
So, let’s continue with the building example.
Both classes and objects symbolize a building, they both have properties and methods.
What are the differences then?
Imaging a class like a blueprint.Classes list all the properties the building needs to have. The building will have windows, rooms, surely a nice color on the facade, a lock on the front gate, an AC unit for when it's hot, a fireplace for when it's cold, etc.
An object, instead, represents the actual building. The actual numbers of windows, maybe the color of the frames, the exact number of rooms, the status of the lock (is the gate closed? is it open?) and so on…
The “Class” Keyword
You have already seen that in order to create an object you need to use the new
keyword. But, new what?
The new element that needs to be created is the instance of the class. Within the class, you will describe all the characteristics that the building must have, such as the number of windows, their color, the number of rooms, etc.
I can also add actions that I need the building to “perform,” like locking the gate, unlocking the gate, adding windows, and turning on the AC.
In order to create a class, you need to use the PHP keyword class
, followed by the open brace. It's good practice to add the brace on a new line.
Then you need the add the properties and after that add the methods that the class requires.
Here is how:
class Building { // building’s properties $numberOfWindows = 10; $colorOfWindows = “red”; $numberOfRooms = 4; $lockClosed = false; // building’s methods /* * The closeLock() method set the lockClosed property to true * This means the lock is closed */ function closeLock() { $this->lockClosed = true; } /* * The openLock() method set the lockClosed property to false * This means the lock is not closed, thus, it is open */ function openLock() { $this->lockClosed = false; } /* * The addAWindow() method add a window to the house */ function addAWindow() { return $this->numberOfWindows = $this->numberOfWindows + 1 ; } /* * The removeaWindow() method remove a window to the house */ function removeAWindow() { return $this->numberOfWindows = $this->numberOfWindows - 1 ; } } $myHome = new Building();
My home now has 10 red windows, 4 rooms, and it is open to everyone that wants to visit me.
The “New” Keyword
The last example finished with the command
$myHome = new Building();
What this new
keyword does is to instantiate a new object from the Building
class and set it in the variable called $myHome
.
I can now call $myHome
’s properties and methods.
$myHome = new Building(); echo $myHome->numberOfRooms; // The output will be 4 echo $myHome->addAWindow(); // The output will be 11
A new element you see in the snippet above is the arrow, ->
.
Do not be intimidated by this symbol, it is just a syntax of the PHP language to get the element you want to select.
Think when you use an array
echo $shoppingList[5];
The two square brackets simply allow the developer to retrieve only the sixth element of the $shoppingList
array (it is not the fifth because array indexes start at 0).
You can also instantiate different buildings and this is one of the biggest pros of using OOP rather than procedural programming.
You can create different objects that will end up having different properties even though they belong to the same class:
$myHome = new Building(); $myNeighborHome = new Building(); echo $myHome->lockClosed; // The output will be false echo $myNeighborHome ->colorOfWindows; // The output will be “red”
Consider that this is just the simplest example, soon you are going to see how can we instantiate the same classes with different characteristics, create relationships among classes, and even invoke methods automatically.
Properties of a Class
By now you should understand that variables within a class are called properties (sometimes also attributes or fields), they are defined as you do for normal variables, but, in a class, you will prefix them with a visibility keyword which you will read about below.
Inside a class, methods and properties need to be accessed using $this->propertyName
for non-static and self::propertyName
for static ones.
Since properties and methods dwell in two different namespaces, you can create a property and a method with the same name and they will not conflict.
class Building { $wifi = 'this is a property'; function wifi() { return 'this is a method'; } }
Methods and Parameters of Classes
Methods are just like functions. I like to think of them as the actions that your class can perform.
We have already seen some examples before:
/* * The openLock() method set the lockClosed property to false * This means the lock is not closed, thus, it is open */ function openLock() { $this->lockClosed = false; } /* * The addAWindow() method add a window to the house */ function addAWindow() { return $this->numberOfWindows = $this->numberOfWindows + 1 ; }
If, for instance, you need to create the car
class, you will have the brake()
method and the throttle()
method, as well as turnLeft()
and turnRight()
.
To add a method you will need the visibility keyword followed by the name of the method you need to create, plus the parenthesis that may or not contain parameters, and, eventually, the braces that start and end the method’s block.
Even in this case, it is good practice to add the braces on a new line.
$this and self::
In order to figure out what $this
and self::
, do I must explain what the static
keyword means.
By declaring static properties and static methods, you will make them accessible without instantiating the class.
I will go over this topic again soon but I just want you to know that it is a very powerful feature of object-oriented programming.
-
$this
is a pseudo-variable and it is used when you need to refer to the variable from within the class. -
$this
is just a reference to the calling object.
class Building { // building’s properties $numberOfWindows = 10; function addAWindow() { return $this->numberOfWindows = $this->numberOfWindows + 1 ; } }
As you can see, $this->numberOfWindows
r efers to the $numberOfWindows
variable and its value is getting retrieved from the AddAWindow()
method.
self::
basically does the same thing but it works on static properties and methods.
class Building { // building’s properties static $numberOfWindows = 10; function addAWindow() { return self::$numberOfWindows = self::$numberOfWindows + 1 ; } }
Conclusion
As you can imagine, there is still a lot of things you need to learn about OOP.
We have only scratched the surface, but this little step you took today will lead you very far, I guarantee it.
I am going to publish the second part of this guide soon so, stay tuned!
This is part one of the article, visit anastasionico.uk for the entire series.
Recommend
-
45
Introduction Object-Oriented Programming (OOP) is a programming paradigm where different components of a computer program are modeled after real-world objects. An object is anything that has some characteristic...
-
60
7 Lessons 40m intermediate
-
29
Java programmers making a move to Python often struggle with Python’s approach to object-oriented programming (OOP). The approach to working with objects, variable types, and other language capabilities taken by Python vs...
-
42
Back in 2015, Brian Will wrote a provocative blog post: Object-Oriented Programming: A Disaster Story . He fo...
-
46
Responses You have 2 free member-only stories left this month.
-
14
Functional Object Oriented Programming 2020-04-21 Due to strange reason lots of people take Object Oriented Programming and Functional Programming as mutually exclusive paradigms. That doesn’t h...
-
24
Type equality in object oriented programming
-
7
Object-Oriented Programming strikes back! Aug 2, 2017 • Also in: oop...
-
6
Object Oriented Programming in PythonSkip to content
-
6
Organizing your code properly is a time-saver when building large applications and working across teams as a programmer. You should always strive to write organized, reusable, and, most importantly, maintainable code so that you can work efficient...
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK