Object-Oriented PHP & PHP Coding Tutorial for Beginners

This is one among elegant Object-Oriented PHP tutorials that will enable you to learn object oriented PHP in very easy manner. This Object-Oriented PHP for beginners in coming section of this post will focus on PHP programming, Object-Oriented PHP, PHP Object-Oriented programming and various PHP coding tutorial too in order to make you more benefited.

 Understanding Object-Oriented Programming

Object-Oriented programming is considered as a coding style which enables the web-developers to congregate identical tasks into classes. However, it lets you to buoy up the code through “don’t repeat yourself” (DRY) principle and is very affable to cultivate.

One most significant and worthy feature of DRY programming is that when a fragment of information alters in your program, generally one change is supposed to upgrade the code. However, one of the major illusion for developers is cultivating the code while data is supposed to be declared most often, which stands for any modification being implemented to the program become more frustrating as they investigate for duplicate data and functionality.

As, OOP is introduces various new syntax and at a glance supposed to be more confounded in contrast of simple procedural or inline code, thus threatens to most of the developers.

Comprehending Objects and Classes

Prior to indulge in nitty gritty insight of the OOP’s finer points, it is necessary to comprehend the fundamental differences between objects and classes. However, this section will take you through building blocks of classes, concerned distinct abilities as well as their uses.

Recognizing the Differences Between Objects and Classes

Lets know the difference between objects and classes with reference to this illustration. A class is something identical to a blueprint for a house. It determine the shape and planning of the house on paper through establishing a link amongst distinct sections of the house defined and planned clearly, even though no existence of the house.

An object is like the actual house built in accordance of that blueprint. However, the stored data in object is like wires, wood and concrete which construct the house. Furthermore, it’s just a aggregation of stuff, if not assembled properly according to the blue print. Thus, when amassed together, results in a useful and organized house.

Classes form data structure and action as well as employ information for Objects building.

In the mean time by identical class, independent multiple object can be created where no object will interfere others. However, following our analogy of construction. It seems to similar to the procedural to built an entire subdivision in accordance of the same blueprint. Where, 150 distinct houses convey same structure and look but comprises distinct families and inside decorations.

Structuring Classes

The syntax of creating a class is very simple and easy; just declare a class in account of class keyword, followed by class name and curly braces {}sets.

After accomplishing this, you can assign a new class and save in a variable through employing a new keyword:

Now, in order to view the contents of the class, you can employ var_damp():

Test this process by incorporating these code snippet in a new file called test.php at your local folder.

Now, you are required to upload this page to your browser at http://localhost/test.php and eventually something will appear should be like this:

With this, you have successfully accomplished your first Object-Oriented PHP script.

Defining Class Properties

Class-specific variables or class, properties are used to add data. However, likewise other regular variable it also works except those who are bound to the object and hence can be accessed only by employing the object. In order to add a property to MyClass, you are required to put the following snippet code to your script:

Where, the keyword public defines the property visibility, about which you will know later in coming next section. Next, through standard variable syntax a name to the property is assigned as well as a value too. (though class properties don’t require initial value).

In context to read this property and final output to browser, you are supposed to reference the object by property you wish to read.

Where the arrow (→) is known as an OOP construct which used to access the method and contained properties assigned to a given object. Moreover, it is possible that multiple instances of a class may exist. So, when an individual object wouldn’t be referenced then the script can’t determine the object to read from.

Therefore, you are required to alter the script in test.php test file in order to read property instead of dumping the entire class through changing the code as listed below.

After reloading your browser you will get following outputs:

I’m a class property!

Defining Class Methods

One most significant amongst class-specific functions is Methods. An object which is capable to perform an individual actions is falls under the class as methods. As for example, in order to create methods which can be set and fetch value of the class property $prop1, include below provided snippet to your code:

Here is a noticeable point that by using $this OOP winks object to referenced themselves. While you are supposed to work within a method, you should employ $this likewise same way as you would employ the name of object outside the class.

However, in context of applying these methods, likewise other common regular function call them also, but first of all you are required to reference the concerned object. Now, modify the value after reading the property from MyClass and then read it again after implementing the alteration below:

After reloading the browser you will get the following:

I’m a class property!
I’m a new property value!

In the case of applying multiple instances of the same class the power of OOP renders to more apparent.

When you will load this result to your browser, it will read as says below:

I’m a class property!
I’m a class property!
I’m a new property value!
I belong to the second instance!

However, you can see here that OOP conveys asunder entities to objects, which tends them to separate easily from distinct snippet of code into small and respective bundles.

Magic Methods in OOP

Towards the endeavor of easier employment, PHP also offer various magic methods or called as special methods which are useful to employ in the case when some specific common actions hit within the objects. Thus, it enables the web-developers to pursue quantity of worthy actions with relative comfort.

Employing Constructors and Destructors

PHP offers a magic method called _construct() which is very helpful when a new object come into existence it called it automatically. Towards clarifying the concept of constructors, include a constructor to MyClass which results in output a message when it designate that a new class has been created:

Note: __CLASS_ says the class name where it is called, however, this is the things known as a magic constant. There are lot of magic constants available that can be read out in the PHP manual.

Following result will appear after reloading the file to your browser:

The class “MyClass” was initiated!
I’m a class property!
End of file.

When an object is destroyed call this function, the _destruct() magic method. It is quite obvious for class cleanup.

It delivers a message when an object is supposed to be destroyed through determining the magic method _destruct() in MyClass:

After determining a destructor, you will got this below assigned result after reloading the test file:

The class “MyClass” was initiated!
I’m a class property!
End of file.
The class “MyClass” was destroyed.

PHP automatically used to unleashed all resources when the end of a file is arrived.

In context to trigger the destructor apparently, by implementing the unset() function you can destroy the object.

After loading to the browser the result changes and appears something like this:

The class “MyClass” was initiated!
I’m a class property!
The class “MyClass” was destroyed.
End of file.

Converting to a String

To check any error when a script try to deliver MyClass as a string, _toString() is an another magic method is implemented.
Attempting to deliver the object as a string without _toString() results in a fatal error. Implement echoto which output the object apart from a magic method.

It shows the following output:

The class “MyClass” was initiated!

Catchable fatal error: Object of class MyClass could not be converted to string in /Applications/XAMPP/xamppfiles/htdocs/testing/test.php on line 40

In order to eliminate this error, you can add a _toString() method:

While attempting to render the object to a string output in a call to getProperty() method. You can upload the test script to your browser in context of viewing the result:

The class “MyClass” was initiated!
Using the toString method: I’m a class property!
The class “MyClass” was destroyed.
End of file.

Using Class Inheritance

In account of extends keyword classes can easily inherit the properties and methods of another class. For example, in order to create a second class which enhances the MyClass and include a method, you are required to put the following snippet in your test file:

Following will be the output, when you will upload it to your browser:

The class “MyClass” was initiated!
From a new method in MyOtherClass.
I’m a class property!
The class “MyClass” was destroyed.

Overwriting Inherited Properties and Methods

You can modify the functionality of an existing method or property simply by overwriting and declare it again in the new class:

It display the output which sits below in your browser:

A new constructor in MyOtherClass.
From a new method in MyOtherClass.
I’m a class property!
The class “MyClass” was destroyed.

Preserving Original Method Functionality While Overwriting Methods
If you want to include some new functionality to an inherited method even buoying up the implemented original method, you can employ parenkeyword with scope resolution operator (::):

It displays result of both the new class’s constructor and parent constructor:

The class “MyClass” was initiated!
A new constructor in MyOtherClass.
From a new method in MyOtherClass.
I’m a class property!
The class “MyClass” was destroyed.

However, perhaps it will be proved as quite obvious and significant for you. Object-Oriented PHP will literally be easy to read and maintain, portable code that will save you precious time and additional efforts of repeating functions most often.

Jason Larue

As a qualified PHP developer, Jason Larue is working with PHPDevelopmentServices to replenish the clients with excellent services at competitive rates. He has years of experience of working as a PHP web developer that truly reflects from the solutions that are delivered to the clients in the form of related projects. His experience has enabled him to emerge as an author who contributes in spreading the information regarding PHP web development through well-written blog posts.