tags:

views:

118

answers:

7

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.

A: 

Without a class you'd still need a structure to hold the set of items you are adding to, updating, and deleting from (retrieving would disappear since you would already have the items).

Ignacio Vazquez-Abrams
+3  A: 

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 :( )

Starx
+10  A: 

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

NullUserException
A: 

Your question goes on a broader level of PHP, you are asking question about the OOP fundamentals. I would recommend you still give a basic read to the main features of OOP programming.

mhitza
A: 

The main difference is scope. Here is a great video (even if in computer voice) about the differences: http://www.youtube.com/watch?v=D8jZ0l_GwXQ&feature=related

cdburgess
That video is really misleading and inaccurate. It seems to suggest that all procedural programming is done using a single global scope. In reality, procedural programming evolved from structured programming, which itself emphasized data encapsulation and limiting the scope of variables. The introduction of variable scopes is not a feature of OOP. The biggest advantage to OOP IMO, is that it allows you to look at your application in terms of nouns/objects instead of just functions/verbs. This is how we naturally think, and it makes programming much more intuitive.
Lèse majesté
+2  A: 

Please note that OOP is 90% about objects and 10% about classes and interfaces. That's why we call it object oriented programming.

I think your question is too general. There is so much articles about OOP over the Internet (You are not limited to PHP articles - OOP is a paradigmat so you can read articles about Java etc.)

Object-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. Programming techniques may include features such as data abstraction, encapsulation, modularity, polymorphism, and inheritance.

Read more about emphrased part of that quote.

Crozin
A: 

I like OOP for one reason. Objects. Think of basketball game. Each player is an object. They all have the class human and the each have a different set of individual skills and attributes. If I was going to program a basketball game it would turn into spaghetti code without OOP. With OOP i can spawn individual humans and name them:

Dan is tall and Bill is fast.

$dan = new Human(Tall->increaseHeight());
$bill = new Human(Fast->increaseSpeed());

Without OOP It would be a mess to make a bunch of humans compete against one another and keep track of their attributes. I don't know alot about OOP, but organization is one reason to like it.

JMC