Can you help me understand PHP Classes a little better?


Can you help me understand PHP Classes a little better?



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




didSelectRowAtIndexPath not showing view

1:



jquery: set variable based on one class from an element that has more than one class
Simply (in fact, extremely simply), classes allow you to organize code in logical units as well as provide containers and templates for user-created objects..
Aliasing a class in Python
Let's say you have a car...


What information does a .NET class have about what is calling it?
A car can has a capacity and people inside..
Class libraries for Java's immense verbosity
class Car {     private $people = array();     private $capacity;      function __construct($capacity) { $this->capacity = $capacity; }      function addPerson($name) {         if(count($this->people) >= $this->capacity) {             throw new Exception("Car is already at capacity");         } else {             $this->people[] = $name;         }     }     function getPeople() { return $this->people; }     function getCapacity() { return $this->capacity; } } 
Now, we can start using those cars:.
C++ privately contructed class
$aliceCar = new Car(2); $aliceCar->addPerson("Alice");  $bobCar = new Car(4); $bobCar->addPerson("Bob"); $bobCar->addPerson("Jake"); 
I now have 2 cars (instances), which holds different data..
In Objective-C, am I allowed to override a method in a subclass that the parent used to conform to a protocol?
echo implode(',', $aliceCar->getPeople()); // Alice echo $aliceCar->getCapacity(); // 2  echo implode(',', $bobCar->getPeople()); // Bob,Jake echo $bobCar->getCapacity(); // 4 
I might also want to have a van, which will have an additional property for doors:.
Can PHP instantiate an object from the name of the class as a string?
class Van extends Car {     private $num_doors;      function __construct($capacity, $num_doors) {         parent::__construct($capacity); // Call the parent constructor         $this->num_doors = $num_doors;     }      function getNumDoors() { return $this->num_doors; } } 
Now let's use that van:.
$jakeVan = new Van(7, 5);  // Van is ALSO a Car $jakeVan->addPerson("Ron"); //Jake is with Bob now, so his son is driving the Van $jakeVan->addPerson("Valery") //Ron's girlfriend  echo implode(',', $jakeVan->getPeople()); // Ron,Valery echo $jakeVan->getCapacity(); // 7 echo $jakeVan->getNumDoors(); // 5 
Now maybe you can see how we could apply those concepts towards the creation of, for example, a DBTable and a User class..
. In fact, it's hard to really start explaining why classes simplify one's life without getting into the concepts of Object Oriented Programming (abstraction, encapsulation, inheritance, polymorphism).. I recommend you read the following book.

It will help you grasp the core concepts of OOP and help you understand why objects to really make your life easier.

Without an understanding of those concepts, it's easy to dismiss classes as just another complication..

PHP 5 Objects, Patterns, and Practice

PHP 5 Objects, Patterns, and Practice. Available at Amazon.com.


2:


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..


3:


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..


4:


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..


5:


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; 


6:


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


7:


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....


8:


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..


9:


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..



82 out of 100 based on 42 user ratings 1342 reviews