An introduction to Object Oriented Programing
Prerequisites
Before I'm going to start, there are a few things I'm assuming you already know:
- Basic usage of all of PHP's basic data-types – numbers, strings, arrays and Booleans.
- A good understanding of using functions.
- Some experience with PHP's excellent documentation.
What is object oriented programming?
WikipediaObject-oriented programming (OOP) is a programming paradigm that uses "objects" – data structures consisting of data fields and methods together with their interactions – to design applications and computer programs.
This might be a bit confusing so let me break it up a bit:
In PHP we have several data types, and most have them have unique functions designated for handing these data types. For example, the array data type has a complete set of functions, such as array_push, array_sort, array_key_exists and so on.
What Classes allow us to do is to wrap a custom data type with a specific set of functions to handle it (which we call methods to distinct them from normal functions).
If we will take the array example, a custom array class will be able to do:
$arr = new MyArr;
$arr->push('a');
$arr->push('d');
$arr->push('c');
$arr->sort();
If ($arr->key_exists(2) echo 'a';
The -> operator tells us that we are calling an object's method (or member, which we will talk about in a bit).
The code for this example would have been simple:
Class MyArr{
protected $arr = array();
public function push($value){
$this->arr[]=$value;
}
public function sort(){
array_sort($this->arr);
}
public function key_exists($key){
return array_key_exists($key,$this->arr);
}
public function get($key){
return $this->ass[$key];
}
}
But it might be a little confusing so I'll do some explaining:
First – what's with the protected/public? Well, this is a very important concept in OOP – which is called encapsulation. We're going to talk about it much more later, but the basics is that it tells PHP who can use these properties – the public declaration means that it can be used by outside code (like our example). Protected means (at least for this point) that the code can only be used from inside the class. There is also a third type – private – which is mostly like protected, only that it cannot be inherited (more on that later). One last thing is that methods and members that were defined this way can only be called on class instances – on objects. You cannot use them without first instantiating an object with the new operator.
Second – the $this variable. When we called the new operator, we created a distinct instance of the class – our object. An object is what we call a specific entity of our new data type – our class. An object has an identity. When we want to access that identity from within the object, we use the $this keyword. This might be a bit confusing, so let's look at the last method get. It receives a key - $key, and return the arrays value of that key. Now look at the next code sample:
$arr1 = new MyArr;
$arr2 = new MyArr;
$arr1->push('a');
$arr2->push('b');
echo $arr1->get(0); // a
echo $arr2->get(0); // b
what happened was that each new call created a new instance, with his own $arr property (which from now on we will call a member). When using $this, the class accessed the specific array for that object.
This was a lot to consume, so lets wrap it up so far:
- A class is a costume data type that holds values – it's members, and a set of behaviors – special designated functions – it's methods.
- An Object is a specific instance of a class, the same way that 1 is a number or 'abc' is a string.
- A member is a class variable. It can be any type of native php types, as well as another object.
- A method is a class's behavior – an internal function.
Already, you might start to grasp some of the beauty of OOP – it brings order to our code. Instead of using all the array_* functions, we can simply use these functions as class methods. This is already implemented in PHP with the file data type – all the file_* functions can also be called as object methods.
But this is only the tip of the iceberg. In order to fully grasp OOP's true power, there is one more important property.
Enter Inheritance
In PHP, like al other object oriented programming languages, classes can inherit their properties from other classes. Now, in most OOP tutorials I've read you will find all those animal->mamel->human analogs, but I find them unproductive, since you won't find yourself programming a human in PHP.
So let's take our MyArr class. It can only use numeric arrays. I want to create a new type of an array – an associative one. But that new type will have some of our previous class – like get, sort, and key_exists. So instead of rewriting it, I'll extend it.
class MyAssocArr extends MyArr{
public function set($key,$value){
$this->arr[$key]=$value;
}
}
$myassoc = new MyAssocArr;
$myassoc->set('a','b');
$myassoc->get('a'); //b
$myassoc->key_exists('b'); //false
$myassoc->key_exists('a'); //true
Notice how simple this was. MyAssocArr inherited all the methods and members of MyArr. As a bonus, MyAssoc is also an instance of MyArr. To see if an object is of a specific class, we use the instanceofv operator –
var_dump ($myassoc instanceof MyArr); //true
There are a few other tricks to inheritance. 1st of all – I mentioned before a 3rd type of visibility – private. When a member or a method are declared private, they will not be inherited.
Another important thing is that classes can override their parent's methods and members. If we were to write a new method in MyAssocArr called get, it would have overridden it's parent method. No worry though – the overridden method can still be accessed using the parent:: operator:
public function get($key){
echo $key;
return parent::get($key);
}
One last thing for today-
Constructors
There are many times when we would want to run specific code whenever an object is created. PHP allows us to do so by defining a special method name - __construct. The __construct method, if defined, will be called whenever a new operator will be used. The method can also receive arguments, like any other function or methods, which will be sent to it on construction. This was a lot of talk so let's code a bit. For this part I will create a new data-type – a user, that must hold an ID and a name:
class User{
private $id=0;
private $name = '';
public function __construct($id,$name){
$this->name = $name;
$this->id = $id;
}
}
$user = new User(1,'arieh');
Very simple, but extremely powerful.
To wrap it up, I want to make it clear – anything, and everything, can be an object. This is so true that in a lot of programming languages, like c#, java, and javascript everything is an object, from numbers to functions. Although PHP allows you to write whole applications without using objects even once, I for one believe that you should write your code only with objects. This might make it a bit more complex, but the benefits are huge – from code reusability through inheritance, to easier maintenance, to readability.
In the next few posts we are going to create our 1st application.
Further reading
All of the above links are taken from PHP's excellent docs. i encourage you to take them time and ream them.