Author: Manuel Lemos
Viewers: 2,671
Last month viewers: 1,063
Categories: PHP Tutorials, PHP opinions
Others do not write classes but reuse other people code written in the form of classes. Others completely refuse to write or reuse other developer classes because they do not see much point in doing it.
Read this article to learn why it is better to develop your PHP projects based on object classes. You may also learn how to convert your global code based classes into properly written classes that you can reuse in multiple projects besides other benefits of using Object Oriented Programming in PHP.
What are PHP Classes?
PHP Classes are the means to implement Object Oriented Programming in PHP. Classes are programming language structures that define what class objects include in terms of data stored in variables also known as properties, and behavior of the objects defined by functions also known as methods.
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..
Contents
Is PHP Object Oriented?
PHP OOPs Concepts with Examples: OOP PHP Project
PHP Classes and Objects: How to Use a Class in PHP?
Object Oriented PHP Example Project
In PHP Why Use Classes?
When OOP Classes are not really necessary?
How do I Migrate my Global Code to Use OOP Classes?
Conclusion about Object Oriented Programming in PHP
Is PHP Object Oriented?
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.
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.
PHP OOPs Concepts with Examples: OOP PHP Project
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
{
public $name;
public $description;
public $price;
public function RetrieveFromDatabase($id)
{
/* ... */
}
public function Display()
{
echo 'Name: ', HtmlSpecialChars($this->name),
'<br>',
'Description: ', HtmlSpecialChars($this->description),
'<br>',
'Price: ', $this->price;
}
};
PHP Classes and Objects: How to Use a Class in PHP?
You can create an object using the new operator. A PHP script can create multiple objects of the same class. You can have two distinct 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 { private $results; private $connection; function __construct($host, $user, $password, $database) { $this->connection = mysqli_connect( $host, $user, $password, $database ); } function Execute($query) { $this->results = ($this->connection ? mysqli_query($this->connection, $query) : false); return $this->results !== false; } function Display() { while(($row = mysqli_fetch_row($this->results))) print_r($row); } }; $host = '127.0.0.1'; $user = 'mysql user'; $password = 'mysql user password'; $database = 'products'; $query = new Query( $host, $user, $password, $database); 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.
Object Oriented PHP Example Project
In a real world project, you would use multiple classes for different purposes. You can use single classes for a given purpose, or combine multiple classes to implement different aspects of that functionality.
Some developers have created libraries of PHP classes that can work together to implement common functionality of PHP applications. This way you can implement projects with much less time and effort by reusing the libraries functionality. Usually those libraries are called PHP frameworks.
In PHP Why Use 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?
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?
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 about Object Oriented Programming in PHP
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.
You need to be a registered user or login to post a comment
1,616,803 PHP developers registered to the PHP Classes site.
Be One of Us!
Login Immediately with your account on:
Comments:
34. Thanks for this. - Cameron Aero (2016-03-21 20:12)
Student Programmer at a 2 - year college... - 0 replies
Read the whole comment and replies
33. reason not defined clearly - Daniel Fotograf (2015-10-30 00:30)
summary... - 2 replies
Read the whole comment and replies
32. Thanks a lot :) - jarim (2014-06-01 21:10)
Thanks a lot :)... - 0 replies
Read the whole comment and replies
31. Very Good Information - Giovanni Delgado (2014-03-10 10:13)
Absolutely Rigth.... - 1 reply
Read the whole comment and replies
30. Very good article for OOP - Vivek moyal (2013-12-02 18:53)
Helpme to understand the concept of OOP in PHP... - 0 replies
Read the whole comment and replies
29. typo - David Svetlecic (2013-11-15 02:42)
typo... - 1 reply
Read the whole comment and replies
28. Nice - Welington miyazato (2013-06-28 06:20)
Nice... - 0 replies
Read the whole comment and replies
27. Great article - Ketil Engmark (2013-04-24 07:59)
especially one part... - 1 reply
Read the whole comment and replies
26. Serialised Objects for Secure Data transmission - Arthur Nicoll (2013-04-17 03:28)
Bets feature of Classes in PHP... - 0 replies
Read the whole comment and replies
11. Performances - Marjan mickoski (2012-06-25 20:42)
Degradation of performances... - 9 replies
Read the whole comment and replies