August 22, 2010

Help understanding PHP classes

Question by Sandro Antonucci

I’m trying to learn how to best use OOP in PHP. Please be aware that even if I studied the theory of this new “world” I didn’t enter the OOP thinking yet obviously.

What’s the difference between using normal, separated functions and putting them in a class as methods?

Let’s say I have a class called “shop”.

It has these methods: retrieveitems, deleteitems, updateitems, additems

Except for the fact that I can call methods inside methods with a simple “$this”, what is the difference between putting them in different functions without a class? I mean, for example, I still can call function deleteitems inside function retrieveitems right? Even if not in a class?

Please help me understand what I’m missing.

Answer by NullUserException

OOP provides, among other things, encapsulation.

class Shop {

    function __construct($items) {
        $this->inventory = $items;
    }

    function deleteItem($item) {
        $key = array_search($item, $this->inventory);
        if ($key !== false)
            unset($this->inventory[$key]);
    }

}

Now you can create instances:

$computerShop  = new Shop(array('ram', 'monitor', 'cpu', 'water'));
$hardwareStore = new Shop(array('hammer', 'screwdriver', 'water'));

And each one of them is independent from each other. If I do $computerShop->removeItem('water'), $hardwareStore should still have water in their inventory. (see it in action) Doing this the procedural way is much messier.


Another cool thing about OOP is that you can use inheritance and polymorphism:

class Animal {

    function eat() {
        $this->hungry = false;
    }

    abstract function speak();
}

class Cat extends Animal {

    function speak() {
        echo 'meow!';
    }
}

class Dog extends Animal {

    function speak() {
        echo 'woof!';
    }    
}

Now both Cat and Dogs can call the method eat() even though they are not explicitly declared in their classes – it’s been inherited from their parent class Animal. They also have a speak() method that does different things. Pretty neat, huh?

Wikipedia:

Object-oriented programming, Encapsulation, Inheritance, Polymorphism

Answer by Starx

One of the most interesting feature I like about classes are encapsulation. You can encapsulate various chains of function into one major function and call them directly. Encapsulation creates an environment where you can protect member objects and properties from being modified outside the class.

Another major part of Classes, is groups. To be able to group all the functions and attributes related to a particular object in one and the capability of making different instances of that classes as objects, is simply magical. Say you have a bunch of functions that refer to each other and pass around pretty much the same arguments. That’s a good sign that those functions belong in a class, and those arguments should be members of the class.

Since you are using PHP, imagine you have created a class which creates a panel. Now you can use this class and create different but similar layouts, like news panel, advertisement panel, product display panel by creating different objects of it, and supplying the content.

You might say this is also possible using functions, but functions cannot provide the scalability and flexibility the class provides.

Inheritance

This is one of the major feature of OOP, you can create parent and child classes to an infinite level. For example, you have created a class car. This class have attributes like wheels, gears, steering have methods like drive(), stop() but you can’t accompany every cars in this world, so now you will creates its child class. In this case, the child classes may be 2WD and 4WD, and again these child classes may also have other child classes with new members and methods. But you can access the members and functions all the way up to its parents, and grand parents.

Polymorphism

This denotes being able to override a function in parent classes. i.e the driving system of a simple car is different that the driving system of 4WD car, so you need to override the previous parent function and replace it with a new function.

Another is Overloading, its the ability to be able to use a function over different parameter cases. For example, for a simple car to drive, it needs engine starts, the gear and acceleration but for modern cars like ferrari, you only needs to start the engine and press the accelerator, you dont need gear, so for these two cases in order to use the method drive(), you supply different no of parameters. And classes make it possible.(But this feature is not available in PHP 🙁 )

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!