tags:

views:

481

answers:

13

I'm fairly new to OOP in PHP, I've made a couple of basic scripts but nothing impressive. All I've really taken from it is that it would probably be easier just make a collection of functions and include them.

The structure of classes seems to just confuse what was otherwise a simple process. And in collating everything into a class it doesn't really add any functionality.

So I'm clearly missing something. Could someone explain what functionality is added by creating classes

+13  A: 

Classes are a notion of object-oriented design (and programming and analysis, respectively), where they are used to encapsulate data and methods.

Other object-oriented programming techniques may include features such as

  • information hiding,
  • data abstraction,
  • encapsulation,
  • modularity,
  • polymorphism and
  • inheritance

From an article .. top-15-best-practices-for-writing-super-readable-code:

Object oriented programming can help you create well structured code. But that does not mean you need to abandon procedural programming completely. Actually creating a mix of both styles can be good.

From http://java.sun.com/docs/books/tutorial/java/concepts/class.html:

In the real world, you'll often find many individual objects all of the same kind. There may be thousands of other bicycles in existence, all of the same make and model. Each bicycle was built from the same set of blueprints and therefore contains the same components. In object-oriented terms, we say that your bicycle is an instance of the class of objects known as bicycles. A class is the blueprint from which individual objects are created.

Finally, a short youtube video about the differences between the procedural and object-oriented programming paradigm ...

The MYYN
The YouTube video is a great find. Thanks!
Dave Jarvis
+3  A: 

A big advantage to OOP is code reuse. An example: Say you design a generic "Socket" class, which communicates with a server at a very low level. Then, I may come along and decide that I want to write an FTP class, which allows a user to download files while connected to an FTP server. I can "subclass" your Socket class and extend its functionality to support FTP, without rewriting your code.

Now, say John wants to write an HTTP class, to interact with HTTP servers. He, too, can subclass your Socket class to accomplish this, without rewriting the low level socket code.

Notice how in this example there was no duplication of socket code; both me and John shared it. Code duplication is bad because if there is an error in the duplicated code, the exact same bug may occur somewhere else in your code and you may not realize it.

More detailed information about classes can be found on Wikipedia.

Mike
Code reuse, especially through subclassing, is *very* overstated. The way you describe it here is, in general, just too good to be true. Unless you specifically design an extensible framework (e.g. Spring) or you are the superclass implementor, subclassing is tedious. In modern OOP the focus has shifted to composition, interface inheritance and polymorphism.
eljenso
A: 

Classes are a way to organize programs. Classes can be used to represent entities in the real world, or artifacts in our programming world, reducing the complexity of programs by allowing us to reason about them in terms of a higher granularity.

It is well-known in psychology that experts organize knowledge into "chunks" to allow them to reason more easily and quickly about their domain. Classes allow us to reason more easily and quickly about our programs.

In addition, classes allow us to group together the knowledge about an entity together with the methods/procedures/functions/operations that are naturally associated with that entity. Again, this provides a natural way to organize the information in our programs.

There are other advantages of classes, such as inheritance, but primarily classes are a cognitive way of organizing program structure to reduce the complexity.

Larry Watanabe
A: 

It would definitely be easy to code in procedural programming (that's what your simple process is called) if your website is small. But as your website grow, you will definitely need to sort things.

For example, you will need classes to act as templates for entities to the database. You might need classes to represent each page, and in a single file you might create multiple pages. Thus these are all advantages of OOP.

In another example you have like 40 over functions. You would want to group them together. Putting them in a class as static methods would definitely help. It'll clean things up so that in future when you come back to the same code, everything looks familiar to you.

thephpdeveloper
+8  A: 

While it may at first look simpler to just use a set of functions and include them, classes have their strong points. Classes can store variables and those variables are there "later."

Here's an edited example from php.net

<?php
$item_name = 'Widget 22';
$item_price = 4.90;
$item_qty = 2;
$item_total = ($item_price * $item_qty);
echo "You ordered $item_qty $item_name @ \$$item_price for a total of: \$$item_total.";
?>

v.s:

<?php
class Item {
  protected $name, $price, $qty, $total;

  function __construct($name, $price) {
    $this->name = $name;
    $this->price = $price;
  }

  function calculate($qty) {
    $this->total = number_format(($this->price * $qty), 2);
  }

  public function __toString() {
    return "You ordered ($this->qty) '$this->name'" . ($this->qty == 1 ? "" : "s") .
    " at \$$this->price, for a total of: \$$this->total.";
  }
}

$widget22 = new Item("Widget 22", 4.90);

$widget22->calculate(2);

echo $widget22;
?>

Another huge benefit is that you can make more of them. Say you want to calculate the price of another item and print it. Instead of having to duplicate all the fancy logic, you can just call new Item and be done.

dmitrig01
A: 

I always thought the same thing until I started using classes--realizing that it is so much simpler and better. You should create those functions that you're mentioning, but gather them all within a class. The functions can then within a class share the same variables, and therefore making it simpler when having to use the same functions multiple times.

The best example I can come up with now is connecting to a database.

Instead of having individual functions that connect, sends a query, fetching the results and closing the connection you could wrap all these functions within a class. This would allow you to communicate to the database multiple times using the same functions, without having to make loads of variables tailored for the specific use on the page.

Eikern
+1  A: 

I have thought exactly the same thing.

I have read a few books on OO-PHP, my favorite being PHP In Action.

Although when I read the books I thought "Hey, this is very useful and interesting information.", I have yet to use a significant amount of OO-PHP.

Simple needs like getting info from the server and JSON-ing it back really dont need OOP. Im sure it is "Best Practice", but for many people's needs it isn't practical. A few classes, like database connection, and similar data handling can be real time savers, but PHP is sometimes easier and quicker to be used only partially OO.

Douglas
A: 

If you're just writing procedural-style functions then slapping them together into a class you're not going to get many of the benefits of OOP. I think that the Open Closed Principle and the Dependency Inversion Principle describe some of the biggest benefits of OOP, which you wont get unless you intentionally design them into your code.

OOP isn't perfectly suited to everything, though. I think procedural programming is well suited to web development. It involves converting a (fairly) simple request into a bunch of HTML, which is a highly procedural task. If it's simpler to include a few functions, there's no point trying to shove an OOP shaped block into a procedurally shaped hole. However, I imagine that OOP would be the better option if the website was very complex.

Tom Dalling
+1  A: 

Just a coupl months back I was posting similar questions about classes, I have been using PHP for a few years now and I really didn't see a need to use classes, they just complicated a simple process like you said, well I finally decided to jump in on the Class train and I am still learning but I am comfortable using them now and WOW I have a completely opposite way of thinking about them now, I think they are the best feature in PHP now!

I will admit they can be overkill for a small application but a large social network site like mine is far from small, it has hundreds of files and now that I am converting over to classes it is structured much better now and easiar to build, update, manage my code and other users could come in and understand my whole site a lot better now that it uses classes. Another great feature is you can break up all those functions you might have into seperate class files and use autoload() function to auto load the correct file only when the class is needed, this is great on a big project too. Classes make things more plug in play.

All I can say is it's kind of one of those things you need to dive into to see the REAL benefits of it.

jasondavis
A: 

To manage complexity.

Edit: Maybe I shopuld elaborate a bit more.

Programs are complex entities and many ways have been proposed historically to tame their complexity.

Procedural programming, functions, structured programming, abstract data types and object-oriented programming are just models to help programmers manage the mental effort that is required to understand a program.

Object programming will not solve everything, and certainly for a small script it is overkill, but it works great for big applications or systems.

My original answer tries to summarize the full content of the humongous Code Complete book: do your best to manage complexity and make your programs understandable for you and your successors. It's great if you think that object programming will help you in this task, but it's even better that you question its convenience and try to find better ways.

Pablo Rodriguez
A: 

In PHP, classes can, at the very least, save you a bunch of include statements. The lazy loading of the __autoload() function is very handy. Also, you can be confident that function names in different includes won't conflict.

To go beyond that, you can start to think of creating an API around a class. Functions which are needed only by other functions within the class can be marked private. And eventually, you should be able to ignore the actual code in your classes, and just think of them as API calls.

If I call Do::stuff($a, $b) I get this response.

And that's all you need to know. You can forget how it works "under the hood" inside the class.

And then, of course, there's classes with non-static functions. These can do various interesting things that normal functions can't.

TRiG