Can you help me understand PHP classes a little better?

I’m kind of a slow learner, I think when it comes to coding, I’ve been studying PHP for a couple of years, and I still don’t understand Classes, so I made some effort to at least understand them a little better.

I use functions for everything. People often comment on me here that they cannot believe that I have a social network site and I do not use classes.

I really don’t understand what benefit you can explain by their advantages, besides the fact that it may facilitate the work of several people on your code?

It seems to me that classes just complicate a simple task

+3
source share
9 answers

Simple (in fact, extremely simple) classes allow you to organize the code in logical units, as well as provide containers and templates for user-created objects.

Say you have a car ... A car can have a capacity and people inside.

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 these cars:

 $aliceCar = new Car(2); $aliceCar->addPerson("Alice"); $bobCar = new Car(4); $bobCar->addPerson("Bob"); $bobCar->addPerson("Jake"); 

Now I have 2 machines (instances) that contain different data.

 echo implode(',', $aliceCar->getPeople()); // Alice echo $aliceCar->getCapacity(); // 2 echo implode(',', $bobCar->getPeople()); // Bob,Jake echo $bobCar->getCapacity(); // 4 

I may also need a van that will have an additional property for doors:

 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 you can use this 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 girlfriend echo implode(',', $jakeVan->getPeople()); // Ron,Valery echo $jakeVan->getCapacity(); // 7 echo $jakeVan->getNumDoors(); // 5 

Now, perhaps you can see how we could apply these concepts to the creation of, for example, the DBTable and User classes.


In fact, it is difficult to begin to explain why classes simplify life without delving into the concepts of object-oriented programming (abstraction, encapsulation, inheritance, polymorphism).

I recommend you read the next book. This will help you understand the basic concepts of OOP and help you understand why objects really make your life easier. Without understanding these concepts, it is easy to dismiss classes as just another complication.

PHP 5 Objects, Templates, and Practice

PHP 5 Objects, Templates and Practice http://ecx.images-amazon.com/images/I/51BF7MF03NL._BO2,204,203,200_PIsitb-sticker -arrow click, TopRight, 35, -76_AA240_SH20_OU01_.jpg

Available on Amazon.com

+17
source

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

Classes are the foundation of OOP . They, in fact, are object drawings. They provide many functions to the programmer, including encapsulation and polymorphism.

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

Structured Example First

 <?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 an example of OOP

 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 obvious that just creating new data structures (objects) is simpler and more controlled, pay attention to the logic in the talk () function in the first example on the talk () methods in the second.

Notice how the former must explicitly check the type of person before he can act? What happens when you add other action functions, such as walk (), sit (), or whatever you can have for your data? Each of these functions will have to duplicate a type check to make sure that they are executed correctly. This is the opposite of encapsulation. Data and functions that use / modify them are not explicitly bound in any way.

While with the OOP example, the correct speak () method is called based on how the object was created. This is inheritance / polymorphism in action. And notice how say () in this example, being a method of an object, is explicitly related to the data it affects?

You are entering a big world, and I wish you the best of luck in your learning. Let me know if you have any questions.

+3
source

In a way, you're right. Classes can complicate simple tasks, and you can certainly do a lot without using them. However, classes also make life easier.

Imagine your life without functions. You will need to use GoTo instructions to group the blocks of code. Ugh. Of course, you could do the same, but you would have to work a lot harder and it would be much harder for you to share your work with others.

Classes provide a neat way to group blocks of similar code. In addition, they make it easy to capture and work with the state.

A good definition of a class is a project for creating objects.

+2
source

Probably the best thing you can do for yourself is to buy / find / borrow an object-oriented programming book. PHP classes are basically the same as other modern languages ​​(Java, C #, etc.), and once you learn OOP, you will understand the classes at the programming level, which is completely language agnostic and can be applied to any OOP project, PHP or otherwise.

+2
source

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

  • Code outside the class cannot manipulate the array that is used to implement the stack.
  • The global namespace will not be polluted by unrelated variables
  • The code that the stack should use can simply instantiate the class (i.e. $ myStack = new Stack ())
+1
source

A class is like a calculator. You can have ten thousand different calculators that do the same, and each of them keeps track of its 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

Each calculator can perform the same tasks and work with the same code, but they all contain different values.

If you have not used classes, you will have to individually create each calculator, assign a variable to it, and copy and paste each calculator that you would like to use immediately.

  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 one class, which is the code for the calculator, and then you can create as many different as you want, each with its own counters.

  class calc
 {
    public $ total;
    function add ();
    function subtract ();
    function multiply ();
    function divide ();
 }
 $ cal1 = new calc;
 $ cal2 = new calc;
 $ cal3 = new calc;
+1
source

I see that you have a lot of great detailed answers, but to make it really simple:

You know what a code block 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 devoted to organizing functions and variables.
If you create many functions, you must be very careful that their names do not collide, and you probably want to organize your functions in separate files in order to group related related functions.

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

 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, each of which has its own addProduct() method (function). This is a small improvement over another piece of code, since the function names themselves have become much shorter, it is obvious that the functions are not designed to work together, and it is easy to add other related functions to one class.

Other classes also allow you to not only group a function together, but also variables. Variables are often worse than functions when it comes to naming, as you need to be very careful not to rewrite variables. By grouping them all in their respective classes, you have less name conflicts. (A related concept is also called a namespace.)

Which classes also allow you to create objects from them. If the class is a plan of related variables and functions, you can build an “actual object” from this plan, even several that act independently, but behave the same. Instead of tracking $shopping_cart1 and $shopping_cart2 and making sure your functions act on the right variable, you simply make a copy of your plan:

 $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 do not need this very often in web development, especially PHP, but depending on your application this may be useful.

Which classes additionally allow you to slightly modify them. Say you have created a large collection of features that act together as a shopping cart. Now you want to create another shopping cart, which basically works the same, 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 in the old shopping cart, but override and modify several specific variables or functions (this is called Inheritance).

There are many more features that the Classes concept gives you, and each of the above items entails a lot more details and features. In general, Classes are used to keep things together that belong to each other, keep things apart that should be separated from each other (namespacing), simplify sequence checking (getters / seters, check variables before replacing them) and much more ...

+1
source

I use classes for database tables.

for example, we have

ID, first name, last name

For this I will use the class

 class user{ public $Id, $name, $lastname public function user($iId){ Id = $iId; firstname = mysql_get('firstname'); lastname = mysql_get('lastname'); } 

for il performance, use getData_functions to retrieve data, not to put it in the constructor. Note that this is just a basic idea above, not an example of how to structure your classes.

But later you can do it for multiple users

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

they make life easier.

But I will be more important to make life easier than faster. Because a poorly designed class can slow things down.

However, for such a function, which is common to my global program, I do not use classes for them.

0
source

As a jokey anecdote, I once described PHP scripts without classes as soap operas are flat and difficult to use in real situations. OO-PHP, on the other hand, is a bit more like real drama; objects are dynamic and can be multifaceted, and although there is a tendency to change between their instances, they are often based on fundamental dramatic archetypes.

Basically, I’m saying that it’s easier to convert and reuse object-oriented code, which simplifies the implementation of open source frameworks and utilities. I find clean PHP scripts to be very difficult to maintain and reuse, and tend to allow for bad security holes, that there are many good, object-oriented utilities that existed before.

0
source

All Articles