I learnt to code in functions and I've looked at a few of the tutorials but simply cannot get my head around OO PHP using objects and classes. I just don't understand the point of them... When I code in PHP I always have an include file with all of my commands in, database connection, inserts, queries, deletes etc so what is the benefit of writing in classes? What specifically can go into a class? Some of the tutorials were easy to follow but they confused the hell out of me. "Okay, so we'll set a class for a name: Class: <?php class person { var $name; public $height; protected $social_insurance; private $pinn_number; function __construct($persons_name) { $this->name = $persons_name; } function set_name($new_name) { $this->name = $new_name; } function get_name() { return $this->name; } } ?> PHP: Output <?php $jimmy = new person; $stefan->set_name("Stefan Mischook"); // directly accessing properties in a class is a no-no. echo "Stefan's full name: " . $stefan->name; ?> PHP: The way I know: <?php echo "Stefan";?> PHP: I just don't get why it has to be so long-winded. Anyway, does anybody know of any decent resources which will show things that I can relate to such as using it for sitewide variables instead of names? Cheers
In this question thread it has been quite clearly explained why and when to use OOP in PHP. http://stackoverflow.com/questions/716412/why-use-php-oop-over-basic-functions-and-when Basically using OOP for the sake of using it is something that you don't need to be doing, because it can lead to more workload if you are just going to use plain data structures. The things which you can use from OOP are inheritance and polymorphism which roughly mean that when you have one base class, but it's functionality is insufficient and you still want to use it for more things you can inherit its data and functions and expand on them in other class(es). A simple example would be if you want to build a GUI system. The first thing you would do is have a base widget class which has properties like size, position and functions for hover and click events, but that is not enough for building a GUI system. You would need separate classes for scrollable areas, text areas, buttons, menus, etc. which would behave differently depending on user input, but would still have something in common which can be inherited from the widget class instead of adding it separately to each class. Another plus is if you want to add some funky functionality to all of the widgets you can actually only edit the widget class and since every other class is inheriting from it, they will have the same functionality. For samples of how OOP is used you can pretty much see the source of any blogging platform or online shop that is written in PHP and see how and why they use it. What you want to ask yourself is what are the specifics of your project and whether or not it can gain something from a OOP realization. If not you can pretty much stick to procedural programming.