Object Oriented Programming Classes in PHP

Introduction

Until recently I thought that articles like this were not necessary because I assumed that the basic concepts about Object Oriented Programming are well known and understood by most PHP programmers.
However, after repling to a question that appeared in the Quora site on how to go from procedural to object-oriented PHP,  I reflected a bit and realized that a great part of the PHP developers do not have basic knowledge Object Oriented Programming (OOP), or if they know what that it is, they do not see much point in using it, so they do not take advantage of OOP benefits in their projects.
Here are are few evidences of the problem:
a) Once in a while I read people ranting about the use of Object Oriented Programming. Some even claim that using objects makes your PHP applications slower and it should be avoided. So they develop all with global code, global functions and variables.
They are certainly not aware of the problems of using global code, probably because they did not have a good programming background and never had the opportunity to learn why Object Oriented Programming is a good thing.
b) Very popular applications like Wordpress are largely written using global functions and variables. Although it seems they have been moving towards a more object oriented approach, a great part of the code is still in the global space.
Having global code in a project is not a sin. You will not go to hell if you write global code, but as I explain below, global code raises several problems that would be better if you would not have to deal with.
Anyway, being Wordpress a very popular PHP project, it sets a bad example for those that try to learn how to do things in PHP and use this project as an example.
c) Some people seem to use Object Oriented Programming but if you ask them why they do it, they are not quite sure. They just seem to be following a practice that they have seen others doing.
Following good practices is a good thing, but you should always have a good idea about what you are doing and why you are doing it, so you can be in full control of your life.
Object Oriented Programming is an abstract concept. It may be simple to demonstrate in practice but the concepts are very abstract. It requires a clear explanation probably with good analogies to teach the basic concepts and clarify why they are important for developers to properly take advantage of OOP.
d) The PHP Classes site is very democratic. It accepts for publication classes from all authors, inclusively classes that practically do the same as many other classes already  in the site. The site is criticized by some more experienced developers for that. That is the price of making the site open to all developers willing to contribute.
Still about 14% of the classes submitted to the PHPClasses site are refused. The classes that are rejected are of two kinds:
1. The author did not submit the package files because they are too many to upload manually. Nowadays this rarely happens because since last year developers are importing large packages automatically from Git, SubVersion or CVS repositories.
2. The author submitted code that implements the described functionality as global code, not OOP classes. This is currently the majority of the cases of rejected packages.
The site is called PHP Classes for being a place to share PHP components in the form of OOP classes. It seems some authors think of classes as of learning classes, not OOP classes.
The site only accepts OOP classes because it is the right way to share components that are meant for reuse. This is explained in more detail below.

For all these reasons this article seemed to be necessary. Nobody knows everything. I hope this helps clarifying the misunderstands.

What are Object Oriented Programming Classes?

PHP OOP Object Oriented Programming Classes
Here is a basic primer about Object Oriented Programming in PHP for those that are not yet familiar with the concepts.
Objects are containers. They contain the definition functions and variables that represent a single abstract entity. This feature of Object Oriented Programming is called encapsulation. It means that a single capsule may contain the definition of multiple functions and variables that are meant to work together.
For instance, if you want to manipulate a product being sold in a e-commerce site, you can have an object that represents that product. It probably contains some variables that define the product name, description,price, etc.. It may also contain some functions to manipulate the object variables, store or retrieve the values of the product from a database, display the product details, etc..
In PHP objects are defined using classes. A class contains all the definitions of functions and variables that describe an object.
Here is a sample of simple product class:
 class Product
 {
   var $name;
   var $description;
   var $price;

   function RetrieveFromDatabase($id)
   {
     /* ... */
   }

   function Display()
   {
     echo 'Name: ', HtmlSpecialChars($this->name),
       '<br>',
       'Description: ', HtmlSpecialChars($this->description),
       '<br>',
       'Price: ', $this->price; 
   }
 };

You can create an object using the new operator. A PHP script can create multiple objects of the same class. You can have two distince products for sale in your e-commerce site defined by the same class.
For instance, if you have for sale the book A and the book B, you can use the same class to manipulate its name, description, price, etc.. Here follows an example of how to create PHP objects:
 $book_a = new Product();
 $book_a->name = 'Book A';
 $book_a->description = 'Some description of book A';
 $book_a->price = 9.95;
 $book_a->Display();

 $book_b = new Product();
 $book_b->RetrieveFromDatabase('id-of-book-b');
 $book_b->Display();

Classes allow you to manipulate information internally without having to use global variables to share information between different class functions.
For instance if you want to retrieve and display database query results, you can have a class with a function to execute the query and another function to display it. They use the class variables $results to store and retrieve the query results handle.
 class Query
 {
   var $results;

   function Execute($query)
   {
     $this->results = mysql_query($query);
     return $this->results !== false;
   }

   function Display()
   {
     while(($row = mysql_fetch_row($this->results)))
       print_r($row);
   }
 };

 $query = new Query;
 if($query->Execute(
   'SELECT name, description, price FROM product'
 ))
   $query->Display();

As you may see, you do not need to use any global functions nor any global variables to share information between the class functions. All the behavior of the products is encapsulated inside the Query class.
Object Oriented Programming provides other important features such as inheritance, which allows creating new classes that are extensions of existing classes. The extension classes may have more functions and variables. They may also redefine functions and variables already defined in the base class.
However, for the purpose of explaining the importance of developing your projects using classes this is enough.

Why it is better to develop your PHP projects using OOP classes?

The main reason why it is better to organize your project code in classes is to avoid collision of names of functions or variables used by different components.
As you may see in the example above, the Product and Query classes have a function named Display.
If you used in the same PHP script components to implement the same functionality but based on global functions and variables, you would have a problem with the fact that different components have functions with the same name, in this case the Display function. Redefining a function with the same name makes PHP exit with a fatal error.
Of course you could avoid that problem adding prefixes to all global functions and variables that you define but obviously that is a drag because you would have to assure those prefixes are unique among all the distinct components you may want to use.
When you want to use components written by other people it may not even be viable because you would be using code that you would not control.
That is also the main reason why the PHP Classes site requires that the components submitted to the site provide the described functionality encapsulated in classes.
The goal of the PHP Classes site is to promote sharing and reuse of work developed eventually by different developers. If you want to combine classes from different developers, the classes can perfectly have functions and variables with the same names, as there will be no name collision.
It may however happen in rare cases, that two classes of different authors have the same name. If the classes have the same name, they are probably for the same purpose, so it is less likely that you may want to use both classes in the same script.
But to avoid the problems caused by that rare possibility, PHP 5.3 introduced a new feature to avoid the collision of class names. That feature is called namespaces. You will hardly ever need this to avoid class name collision, but it is possible that you use two different frameworks that have classes with the same names. That is a case where namespaces may help solving that problem.
In sum, classes allow you to organize better the code you use in your applications by making you put the code that manages related data in the same container, avoiding name collision problems and even promoting reuse of your code eventually of multiple developers in a single project.

When OOP Classes are not really necessary?

Creating and using classes is not a big deal in terms of effort, but there are very simple cases where classes are not really needed.
For instance if you have developed some code that is not meant to be used more than once and there is no chance that the names of any global functions and variables for different purposes collide, using classes is not necessary.
But you never know about the future. In the future your scripts may become more complex and you need to combine components of different sources for different purposes, so it is always better to start using classes from the beginning.

How do I migrate my global code to use OOP classes?

Some people refer to global functions and variables as procedural code. Procedure is just a different name for function. Classes also have functions, so classes also have procedural code. So it is more accurate to call global code to code that uses global functions and variables instead of procedural code.
Migrating global code to OOP classes is simple. Just declare a class and shove your related global functions and variables inside the declaration.
Then you need to change any accesses to variables and functions using the $this-> operator. $this means the current object when you are inside a class function. For instance if you have a global variable named $variable_name and a function named function_name, just change the references to them to $this->variable_name and $this->function_name().
Example global code:
 $variable_name = 'foo';

 function function_name()
 {
   global $variable_name;

   echo $variable_name;
 }

 function_name();

To use the class for the application code you need to create a new object using the new operator. Then you can access the functions from the outside of the class using $object->function_name() and variables using $object->variable_name .
Migrated class based code:
 class class_name
 {
   var $variable_name = 'foo';

   function function_name()
   {
     echo $this->variable_name;
   }
 };

 $object = new class_name;
 $object->function_name();

There are also other interesting OOP features like constructor and destructor functions, access protection modifiers, static functions and variables, etc.. but I do not want to go there. This is enough to get you started and migrate your global code to OOP PHP classes.

Conclusion

This article was meant mainly for developers that either were not aware of the basic Object Oriented Programming concepts or were aware of those concepts but were not quite sure why OOP is a good thing to be applied in every day PHP programming.
These developers are abundant in the PHP market because PHP attracted many developers that did not have a serious programming background. The point of the article was not to put them down but rather to try to educate them using simple and hopefully easy to understand analogies.I hope that goal was achieved.
As I said above, nobody knows everything, so it is never too late to learn, even when we are talking about basic concepts like those presented in this article, which more mature developers know very well.
Please forward this article page URL to other fellow developers that you feel could benefit from the knowledge shared in the article.
Other than that, please post a comment if you have questions or disagree of anything about the presented concepts.

Comments

Popular posts from this blog

PHP / SQL Security – The Big Picture

PHP / SQL Security – SQL Commands and Non-String Variables

Top 50 Web Hacking Techniques