Object-Oriented Programming In PHP – Part I

Welcome to Object Oriented Programming in PHP. According to Wikipedia , Object-oriented programming(OOP) is a programming paradigm that represents concepts as objects that have data fields (attributes that describe the object) and associated procedures known as methods. An object is an instance of a class – that is, you use a class to create an object. The easiest way to understand OOP is using a real-world example.

Looking at the above image makes our work really easier here. In real life, there is something called a car. But you can’t just walk to your friend’s house and say I own a car and assume that they will automatically know what type of car you have. So, in other words, our car is a class and from that car class, we can create different kinds of cars(objects) like Toyota, Ford, Chevy etc. Oh, don’t forget the VW Bug!

To make this a little understandable, we can break the car concept into data fields and methods. Every car has some color(attribute), and most importantly they move(method). What else can you think of? A car can either be on or off. The other fact is that different cars have different other properties. Think of them!

Another good example is a cookie-cutter. You can think of a cookie-cutter as a class and the cookies themselves as objects. Using your cookie-cutter, you can create all shapes of cookies, using different recipes.

Encapsulation

One of the biggest advantage of OOP is its capability to support and encourage encapsulation – also known as data hiding. Essentially, access to the data within an object is available only via the object’s operations, known as the interface of the object.

Polymorphism

Polymorphism means different classes can have different behaviors for the same operation. Consider having a class Car and a class Bicycle. They can both have different move operations. Polymorphism is more a characteristics of behaviors than it is of objects. In PHP, only member functions of a class can be polymorphic.

Inheritance

Inheritance allows you to create a hierarchical relationship between classes using sub-classes. If you are asking whether this works like a son inheriting a million dollars from his father or not, then you are thinking right! A subclass inherits attributes and operations from the superclass. An example could work like this: we both know that a car and a bicycle have certain things in common. You could then use a class called vehicle that contain a color attribute and a move operation that all vehicles have. You can simply then have both car and bicycle classes inherit from vehicle class – how nice right?

Using inheritance might save you work if operations can be written once in a superclass rather than many times in separate subclasses. It might also allow you to more accurately model real-world relationships. If a sentence about two classes makes sense with  “has-a” between the classes, inheritance is probably appropriate. The sentence ” a car is a vehicle” makes sense, but the sentence “vehicle is a car” does not make sense because not all vehicles are cars.Therefore, car can inherit from vehicle.

Creating Classes, Attributes and Operations

Let us get our hands dirty here by …you guessed it, creating classes, attributes and operations in php. When creating a class, the keyword class must be used.

Constructors

Most classes have a special type of operation called a constructor. A constructor is calledwhen an object is created and also normally performs useful initialization tasks such as setting attributes to sensible starting values or creating other objects needed by the object.

A constructor is declared the same way as other operations inside a class but has the special name __construct() and although you can manually call a constructor, its purpose is to be called automatically when an object is created.Time for an example:

#PHP supports function overloading – providing more than one
#function with the same name with different numbers or types
#of parameters!
?>
[/php]

Destructors

Just like constructors, there exist destructors. They are special in the sense that they don’t take any parameters and declared as __destruct(). When all references to a class have been unset or fallen off a scope, it gets destroyed. If you then want to have some functionality executed before the class is destroyed, you use the destructor!

Instantiating a Class

After declaring your class, you need to create an object – a particular individual that is a member of the class. You can then do something with it. As I mentioned earlier, it is called instantiating or creating an instance of a class. You create an object by using the newkeyword. When you do so, you need to specify which class your object will be an instance of and provide any parameters required by the constructor. Time for an example:

#Running the above code will result in: guessed it?
#Constructor called with parameter: first
#Constructor called with parameter: second
#Constructor called with parameter:
?>
[/php]

Using Class Attributes

Within a class, you have access to special pointer called $this. If an attribute of your current class is called $attribute you refer to it as $this->attribute when either setting or accessing the variable from an operation within the class.

#Since the $attribute variable is declared as [public],
#we can access it outside and even change the value!
?>
[/php]

Doing what we did above(accessing attributes and changing their values outside a class is obviously not a good idea.To avoid such a problem, we take advantage of OOP’s encapsulation. We enforce it by using __get and __set functions. These functions are commonly known as setters and getters or accessor functions. Example:

Now our above code provides minimal functions to access our attributes. Basically, our __get function returns the value of the attribute with the same name as the one passed in ($name). __set() on the other hand takes a name of an attribute and a value, then sets the value of the attribute to the value passed in!

One thing to remember is that you do not call __get and __set functions directly. You may be asking, so how do we then call them? Here is the thing: when you instantiate an object like this:

[php]

< ?php
$a = new classname();
?>
[/php]

You can then use __get() and __set() functions to check and set the value of any attributes: If you type:

[php]
< ?php
$a->$attribute = 5;

?>
[/php]

The above statement implicitly calls __set() with the value of $name set to “attribute” and the value of $value set to 5. You need to write __set() to do error handling.

The __get() function works in a similar way. If, in your code, you reference

[php]
< ?php
$a-> attribute;
?>
[/php]

this expression implicitly calls the __get() function with the parameter $name set to attribute. It is up to you to write the __get() function to return the value.

Access Modifiers Debunked

public – this is the default option. That means that failure to declare an access modifier on an item makes it public. The particular item will be accessible both in and outside the class.

private – this means that the marked item is only accessible within the class. You may also declare some methods as private – for example if they are utility functions used only inside the class. Items that are private will not be inherited.

protected – this means the marked item can only be accessed within the class. It also exists in subclasses! Think of this as halfway between private and public.

#Since class B extends class A, you can access both
#operation1() and $attribute1
#NOTE: inheritance works only in one direction – that is:
#a subclass can only inherit from the superclass and not
#the other way round.
#———–CONSIDER THIS NOW——————–#

I am going to stop here then continue tomorrow. I hope you found this helpful. If you have any questions or errors you might have spotted, let me know. There are just a few more concepts that should fit into a single post bringing this OOP topic to an end. Stay safe and hope to see you soon! Please drop me a line in the comment section.

Written By Elisha Chirchir

Elisha Chirchir is a software developer. He is also the founder of Simple Developer and co-founder of Instinctive Software Solutions. On any given day, he works on both Android and Web Development. During his 'free time', he offers training to those interested in learning how to code in php, java, python, javaScript etc. You can easily find him on StackOverflow Android chatroom or on Twitter @Eenvincible