tags:

views:

267

answers:

9

I am kind of a slow learner I guess when it comes to coding, I have been learning PHP for a couple of years and I still don't understand Classes so it's time I put some effort in to at least understanding them a little better.

I use functions for everything. People often make comments to me on here that they can't believe I have a social network site and I don't use classes.

I really do not understand the benefit of them can you explain the benefits besides it supposedly being easiar for multiple people to work on your code?

To me it seems like classes just complicate simple task

+2  A: 

In some ways, you are correct. Classes can complicate simple tasks, and there certainly is a lot you can accomplish without using them. However, classes also make life a lot easier.

Imagine your life without functions. You would have to use GoTo statements to group together blocks of code. Yuck. Sure, you could accomplish the same things, but you would need to work a lot harder and it would be a lot more difficult for you to share your work with others.

Classes provide a neat way to group together blocks of similar code. Also, they allow you to capture and work with state very easily.

A good definition of a class is a blueprint to create objects.

Robert Venables
Am I right to say that classes just group functions together?
jasondavis
like I have 5 different date/time functions, they could all be added to 1 date/time class?
jasondavis
They are meant to group together related data, and the functions that operate on that data.
databyss
You are partially correct, classes group functions (or methods) based on their primary purpose. You may have a static database class with all database related methods residing in it. But you may also have multiple classes with database methods in each one... Have a look at this; http://www.killerphp.com/tutorials/object-oriented-php/
Christian
That is one reason to create a class - but certainly not the only one. And yes, five different date/time functions could be added to one date/time class - Most likely as static members.
Robert Venables
Static methods versus ordinary functions make pretty much no difference in PHP, apart for the pseudo-namespace they offer.
Ionuț G. Stan
+1  A: 

With classes you can do something like

class Stack {
  private $theStack = array();

  // push item onto the stack
  public function push(item) { ... }

  // get the top item from the stack
  public function pop() { ... } 
}

This simple example has some benefits.

  1. Code outside the class cannot manipulate the array that is used to implement the stack
  2. The global namespace is not be polluted with unrelated variables
  3. Code that needs to use a stack can simply create an instance of the class (i.e. $myStack = new Stack())
Lawrence Barsanti
The best thing bout classes ^^
Shahmir Javaid
thanks for the example, you mention code outside the class cannot manipulate the array, I guess I don't follow because if you are coding then I don't see where anything would manipulate it unless you wanted it too and coded it to do so. Maybe i'll understand someday
jasondavis
hes talking about encapsulation. which basically means data hiding to keep you (the programmer) from accidentally creating overriding $theStack in the global namespace. in a world filled with functions and no encapsulation you're forced to have $theStack in the global namespace. Imagine 6 months later and 600 lines below the initialization of $theStack you create it again forgetting it already exists. you override its value and your program behaves unexpectedly. Classes allow modularity and easy maintenance.
centr0
+1  A: 

Probably the single best thing you can do for yourself is to buy/find/borrow a book on Object Oriented Programming. PHP classes are fundamentally the same as other modern languages (Java, C#, etc.), and once you learn OOP you will understand classes at a level of programming that is completely language-agnostic and can be applied to any OOP project, PHP or otherwise.

zombat
+7  A: 
Andrew Moore
+1 - Great description
Robert Venables
+1 for the book
Randell
thanks for the example code, its easiar to understand by example. To me not knowing classes, that seems like so much more code than if you did it with a few functions
jasondavis
**@jasondavis:** But then how can you have multiple cars with functions? Using arrays and passing the array every single time? And how are you guarantied that you don't have more people than the capacity?
Andrew Moore
I recommend taking a look at the book.
Andrew Moore
+1  A: 

A class is like a calculator. You can have ten thousand different calculators that do the same thing, and each of them keep track of their own values and data.

$cal1 = new calculator;
$cal2 = new calculator;

$cal1->add(5);
$cal2->add(3);

echo $cal1->show(); // returns 5

echo $cal2->show(); //returns 3

Every single calculator can do the same tasks, and run on the same code, but they all contain different values.

If you were not using classes, you would have to individually create each calculator, assign it a variable, and copy and paste for every calculator you wanted to use at once.

function add_calc_1();
function add_calc_2();
function add_calc_3();
function subtract_calc_1();
function subtract_calc_2();
function subtract_calc_3();
function multiply_calc_1();
function multiply_calc_2();
function multiply_calc_3();
function divide_calc_1();
function divide_calc_2();
function divide_calc_3();

$total_1;
$total_2;
$total_3;

Instead, you can define a single class that is the code for a calculator, and then you can create as many different ones as you want, each with their own counters.

class calc
{
   public $total;
   function add();
   function subtract();
   function multiply();
   function divide();
}
$cal1=new calc;
$cal2=new calc;
$cal3=new calc;
Chacha102
Please revise your code. It pretty much makes no sense.
Ionuț G. Stan
I shortened it a little. I took out all the functions 'insides', mainly to illustrate the point.
Chacha102
Took out the PHP5 stuff too.
Chacha102
A: 

I use classes for my database tables.

for Example we have

Id, firstname, lastname

For this i will use a class

class user{

    public $Id, $name, $lastname

    public function user($iId){

      Id = $iId;
      firstname = mysql_get('firstname');
      lastname = mysql_get('lastname');
}

for performance il use getData_functions to retrieve the data rather than putting them in the constructor. Note the above is just a major idea rather than example of how to structure your classes

But later you can do this for multiple users

while(mysql_get('Id')){

    $user = new user('Id');
    $print $user->firstname . " " . $user->lastname;
}

they make life easier.

But i will more importantly that making life easier dosent mean its faster.. Because a badly designed class can slow things down.

However for such function that are generic to my global program i dont use classes for them.

Shahmir Javaid
A: 

As a jokey anecdote, I once described PHP scripting without classes as like soap operas -- flat, and difficult to reuse in real-life situations. On the other hand, OO-PHP is a bit more like real drama; objects are dynamic, and can be multi-faceted, and while there tends to be variation between their instantiations, they are often based on fundamental dramatic archetypes.

Basically what I'm saying is that it's easier to repurpose and reuse object-oriented code, which makes implementing open-source frameworks and utilities easier. I find pure scripting in PHP to be extremely difficult to maintain and reuse, and tends to allow for bad security holes that there are a lot of good, preexisting object-oriented utilities for.

Robert Elwell
+2  A: 

This is a huge topic and even the best answers from the best SOers could only hope to scratch the surface, but I'll give my two cents.

Classes are the foundation of OOP. They are, in a very basic way, object blueprints. They afford many features to the programmer, including encapsulation and polymorphism.

Encapsulation, inheritance, and polymorphism are very key aspects of OOP, so I'm going to focus on those for my example. I'll write a structured (functions only) and then an OOP version of a code snippet and I hope you will understand the benefits.

First, the structured example

<?php

function speak( $person )
{
  switch( $person['type'] )
  {
    case 'adult':
      echo "Hello, my name is " . $person['name'];
      break;
    case 'child':
      echo "Goo goo ga ga";
      break;
    default:
      trigger_error( 'Unrecognized person type', E_USER_WARNING );
  }
}

$adult = array(
    'type' => 'adult'
  , 'name' => 'John'
);
$baby = array(
    'type' => 'baby'
  , 'name' => 'Emma'
);

speak( $adult );
speak( $baby );

And now, the OOP example

abstract class Person
{
  protected $name;

  public function __construct( $name )
  {
    $this->name = $name;
  }
  abstract public function speak();
}

class Adult extends Person
{
  public function speak()
  {
    echo "Hello, my name is " . $this->name;
  }
}

class Baby extends Person
{
  public function speak()
  {
    echo "Goo goo ga ga";
  }
}

$adult = new Adult( 'John' );
$baby  = new Baby( 'Emma' );

$adult->speak();
$baby->speak();

Not only should it be evident that just creating new data structures (objects) is easier and more controlled, pay attention to the logic in the speak() function in the first example, to the speak() methods in the 2nd.

Notice how the first one must explicitly check the type of person before it can act? What happens when you add other action functions, like walk(), sit(), or whatever else you might have for your data? Each of those functions will have to duplicate the "type" check to make sure they execute correctly. This is the opposite of encapsulation. The data and the functions which use/modify them are not connected in any explicit way.

Whereas with the OOP example, the correct speak() method is invoked based on how the object was created. This is inheritance/polymorphism in action. And notice how speak() in this example, being a method of the object, is explicitly connected to the data it's acting upon?

You are stepping into a big world, and I wish you luck with your learning. Let me know if you have any questions.

Peter Bailey
thanks for the example it's nice seeing it in a way that I understand and a way that I don't, it's like a whole different language
jasondavis
A: 

I see you got a lot of great detailled answers already, but to keep it in really simple terms:

You know what a block of code is.
You know that if you want to reuse a block of code, you put it in a function.
So far so good. Now, Classes are about organizing functions and variables.
If you create a lot of functions, you have to be really careful that their names don't clash, and you will probably want to organize your functions in separate files to keep related functions grouped together.

At its very simplest, Classes help you to group related functions into one class of functions. Instead of

add_product_to_shop();
add_product_to_cart();
add_product_to_wish_list();

you group them inside a class:

Shop::addProduct();
Cart::addProduct();
WishList::addProduct();

Here Shop, Cart and WishList are Classes that each have their own addProduct() method (function). That's a slight improvement over the other code snippet, as the function names themselves have become a lot shorter, it's obvious that the functions are not intended to work together and it's easy to add other related functions to the same Class.

What Classes further allow you though is to not only group function together, but variables too. Variables are often worse than functions when it comes to naming, as you need to be really careful not to overwrite variables. By grouping them all in their own respective Classes, you have less of a naming conflict. (A related concept to this is also called Namespaces.)

What Classes also allow you to do is to create objects from them. If the Class is the blueprint for related variables and function, you can build an "actual object" from this blueprint, even several, that act independently of each other, but behave the same. Instead of keeping track of $shopping_cart1 and $shopping_cart2 and making sure your functions act on the right variable, you just make a copy of your blueprint:

$cart = new Cart();
$cart->addProduct($x);

$anotherCart = new Cart();
$anotherCart->addProduct($y);

// $cart takes care of product $x, $anotherCart of product $y.
// No extra overhead needed to duplicate functionality
// or to make sure the addProduct() function adds to the right cart.

You don't need this very often in web development, especially PHP, but depending on your application it can be useful.

What Classes further allow you is to slightly alter them. Say you have created a great collection of function that act together as a shopping cart. Now you want to create another shopping cart that basically works the same way, but has some slight differences (say discounts should be calculated immediately). You can create a new Class and specify that it should act exactly the same as the old shopping cart, but override and alter a few specific variables or functions (this is called Inheritance).

There are a lot more possibilities that the concept of Classes enable you to do, and each of the above points entail a lot more details and specifics. Overall, Classes are used to keep things together that belong together, keep things apart that should be apart (namespacing), enable easier consistency checks (getters/setters, validating variables before changing them) and more...

deceze