Doing it the OO way

Post all your tuts or request for tuts here.
Post Reply
Xaleph
Posts: 897
Joined: Mon Feb 07, 2011 2:55 am

Doing it the OO way

Post by Xaleph »

Hi fellow members, I had written a tutorial before here, on regex or something like that but I guess it`s time for a follow up on what OO is.

OO = Object Oriented

What does this mean? In short: an object is "something." In the real world it`s touchable, like a car. A car is comprised of different parts, like wheels, an engine, a steering wheel et cetera. All these different carparts are objects as well.

What OO does is actually quite similiar, you create a Car object. On that Car object, you add other Objects like an engine or wheels. The whole idea behind this is so you "filter" out information. The other thing about these parts is that they belong to something, right? An engine belongs to a car So you could say that the engine is an extension of the car.

An engine itself can have parts too, vauls, pressure pumps, all these parts of an engine belong to an engine. All cool right?

OK time to get to OO land. What does this mean? Well, first of, when we create a Car object, we don`t want to know what engine it`s using, only that the Car object is actually using one. if we did want to know what engine we have, we could ask the Car object for it, and it would respond in saying what engine it was. However, the engine doesn`t give all information as to what pumps and vauls are used, so we can ask the Engine object for it, please tell us what objects you have inside.

This whole extending things ( Engine extends Car or Vaul extends Engine ) is called: inheritance. Why call it like this? because a car example sucks.

Let`s do another one, let`s say we have an Animal Object.
We have 2 sorts of animals right? vertibrate and invertibrate

Now, what do ALL animals have? A biological name for example
Both vertibrate and invertibrate have those properties ( < important )
What does a vertibrate animal have?
A vertibrate! So the properties for a vertibrate object is that is has a vertibrate.
Now, what kinds of vertibrate are there?
There are fish, amphibians, reptiles, birds, and mammals.

Ok, let`s focus on mammals for now.
So we now have a mammal object which extends a vertibrate ( and animal )
What are key properties for mammals?
Well, for one, the give birth to live young, there`s a property we can share for all mammals.
Ok, next up: what kinds of mammals do you have?
Enough, like 5000 or something, which is too much. There are some more categories, but i`m going to pick cat like mammals

So CatLikeMammals extends Mammals ( which extends Vertibrate which extends Animal )
What`s specific on catLikeMammals? They have hair, have 4 legs, are carnivor, grow a tail, et cetera. All properties CatLikeMammals have.

In code this would look like:

Code: Select all

<?php
class Animal 
{
        public $biologicalName = 'Animal';
}

class Vertibrate extends Animal 
{
       public $vertibrate = true;
}

class Mammal extends Vertibrate 
{
       public $givesBirthToLiveYoung = true;
}

class CatLike extends Mammal 
{
      public $hasFourLegs = true;
      public $hasHair = true;
      public $hasTail = true;
      public $isCarnivore = true;
}

class Lion extends CatLike 
{
     public $height = '50inch';
     public $length = '200inch';
     public $width = '30inch';
     public $livesIn = 'Africa';
 
}
?>
Ok, I added a Lion class to the php, so we`re clear.

Ok if i wanted to create a Lion, in PHP ( or any other language ) I use the new keyword:

Code: Select all

<?php
$lion = new Lion;
?>
The cool thing about this is now we have not 5 properties ( height, width, length, location ) but we have ALL properties from the previous classes as well!

So I can now get to so if it is a vertibrate or not:

Code: Select all

if($lion->isVertibrate){
  echo "Yay, i`m a vertibrate";
}
So in short: The lion now has all properties from all the classes in our example, this is obviously because i only created 5 classes, and each one extended the previous one, but you get the point right?

A lion has UNIQUE characteristics like it`s height, width, average weight and location. These are properties ONLY for lions ( in our example ) So only a Lion Object can access them.

Now, there`s a problem: we have a biological name set in our Animal object. A lion`s biological name is not "Animal". It should be "Panthera leo."
So how we change that?

Well, we add a constructor to our Lion object. A constructor is the FIRST function ( = method in OO terms ) that will be executed once we create a new Lion object.

How do we do this?

Code: Select all

class Lion extends CatLike
{
public function __construct()
{
}
}
Remember, this __construct() is a special functioname in PHP, every language has it`s own form. In Java for example you just use the name of the class itself. So the constructor in java would be public Lion(){}

Oh, while we are on the topic, in PHP you can also use the name of the class as the constructor. So public function Lion(){} works pretty much the same. But __construct() is recommended.

Ok, we have a constructor, what`s so special about that? Well, like I said, it will be executed ALLWAYS. Regardless of anything.
Now, we know the original name for a lion, let`s change that!

Code: Select all

public function construct(){
       $this->biologicalName = "Panthera leo";
}
What did we do here? Well, we changed the biological name of our Lion object to Panthera leo. Despite the fact that every animal has a name, they don`t have the same names, so we should change it. As we did.

Also, if you looked at the code and was all like "uh Xaleph, what`s this $this thing?" Glad you noticed! The THIS keyword is a reserved name for objects. $this allways refers to it`s object. So in our example $this refers to the Lion object.

However, look at the following code:

Code: Select all

<?php

class Lion extends CatLike
{ 
     function setCuteNickname($name)
     {
           $this->nickname = $name;
     }

     function getCuteNickname()
     {
           return $this->nickname;
     }
}

$lionOne = new Lion();
$lionTwo = new Lion();

$lionOne->setCuteNickname("Snuggles");
$lionTwo->setCuteNickname("Gorgeous");

echo $lionOne->getCuteNickname(); // what will it produce?
echo $lionTwo->getCureNicknime();  // and this one?
Please think about it. The $lionOne will have a cute nickname Snuggles, and $lionTwo will have a nickname Gorgeous. We may have written only 1 class, we created 2 objects! Very important. There`s a difference between a class and an object. An object is an instantiation of a class.

There are a plethora or rules out there, but that`s all for the next time. I hope you like the tutorial so far, if anyone wants to see a part 2, i`m glad to write it!
User avatar
Nexus
Posts: 293
Joined: Sat Jun 18, 2011 10:42 pm

Re: Doing it the OO way

Post by Nexus »

Very nice tutorial! Nice post as well! Opened my eyes a lot to OO in PHP, never really grasped onto it until now! Thanks for this! :)
User avatar
Jackolantern
Posts: 10891
Joined: Wed Jul 01, 2009 11:00 pm

Re: Doing it the OO way

Post by Jackolantern »

The webpage-based mechanics of PHP actually work really well with the OO paradigm. A basic way of using OO in PHP is to make a page class, and then subclass it (inherit from it). Those subclasses will be for independent pages, and they will handle nearly all aspects of that page.

Of course, that is really the most basic usage of OO in PHP, but one you will still see often. A more advanced usage, and one that is gaining in popularity fast is the MVC pattern. However, most of the time it is not good time usage to make your own MVC framework, as there are already many great ones out there, ranging in complexity and weight from lightweight and straightforward (such as CodeIgniter), to heavy and representing an almost all-inclusive platform (such as Zend Framework).
The indelible lord of tl;dr
Xaleph
Posts: 897
Joined: Mon Feb 07, 2011 2:55 am

Re: Doing it the OO way

Post by Xaleph »

Hope you like it.

@jack: yes MVC works quite well, most frameworks implement the MVC pattern. However, this tutorial is not directly aimed to learn that stuff, rather just a quick intro in OO.
User avatar
Jackolantern
Posts: 10891
Joined: Wed Jul 01, 2009 11:00 pm

Re: Doing it the OO way

Post by Jackolantern »

Ohhh, I know lol. I was just giving a brief survey of the OO landscape in PHP for Nexus and anyone else interested :)
The indelible lord of tl;dr
ConceptDestiny
Posts: 261
Joined: Wed Apr 28, 2010 8:35 am

Re: Doing it the OO way

Post by ConceptDestiny »

Very nice tutorial! :)
User avatar
hallsofvallhalla
Site Admin
Posts: 12023
Joined: Wed Apr 22, 2009 11:29 pm

Re: Doing it the OO way

Post by hallsofvallhalla »

Nice
User avatar
Zak Zillion
Posts: 112
Joined: Thu Apr 07, 2011 12:55 am

Re: Doing it the OO way

Post by Zak Zillion »

So for building a game would you recommend OOP? Also again for a game would you recommend CodeIgniter?
"Any intelligent fool can make things bigger, more complex, and more violent. It takes a touch of genius -- and a lot of courage -- to move in the opposite direction." - Albert Einstein

Old Project(s):
The Dark Flame
Xaleph
Posts: 897
Joined: Mon Feb 07, 2011 2:55 am

Re: Doing it the OO way

Post by Xaleph »

OO is good for large programs, depending on your game, yes i would recommend OO programming. It drastically reduces codebase to maintain and you don`t have to repeat yourself every time. But then again, to set it up takes more code so it depends on the program/application.

Games however, if i understand correctly are allways multithreaded and thus will allways have OO in there. Having a main loop etetera, in browser games however, that`s not the case. And in engines like Unity, you don`t really need it, because you can script your game in javascript, which by the way is OO anyway.

Oh CodeIgniter can be used, it`s a lightweight framework and easy to learn, but if you want OO you don`t __need__ CodeIgniter, you can use other frameworks as well. CodeIgniter is written in OO and thus using it, but OO is not equal to CI whereas CI is not equal to OO. OO is just a different approach to programming, CI only uses OO.
User avatar
Jackolantern
Posts: 10891
Joined: Wed Jul 01, 2009 11:00 pm

Re: Doing it the OO way

Post by Jackolantern »

As Xaleph touched on, OO can drastically reduce the issues with maintenance. If all your code is written procedurally, all mixed in with the HTML, it is really a nightmare to go back and add new features later. That is called "spaghetti code", and can render an application useless down the line, where it must be trashed and re-written to support new features. This is because you have so deeply "coupled" your code. This means that many parts rely on many other parts, and changing one piece of code causes a tsunami of errors and code breakages which can be almost impossible to fix in such a primitive debugging environment as PHP.
The indelible lord of tl;dr
Post Reply

Return to “Tutorials”