Object-Oriented Programming with PHP5

4.5 (2 reviews total)
By Hasin Hayder
  • Instant online access to over 7,500+ books and videos
  • Constantly updated with 100+ new titles each month
  • Breadth and depth in over 1,000+ technologies
  1. OOP vs. Procedural Programming

About this book

Some basic objected-oriented features were added to PHP3; with PHP5 full support for object-oriented programming was added to PHP. Object-oriented programming was basically introduced to ease the development process as well as reduce the time of development by reducing the amount of code needed. OOP can greatly improve the performance of a properly planned and designed program.

This book covers all the general concepts of OOP then shows you how to make use of OOP in PHP5, with the aid of an ample number of examples.

Publication date:
December 2007
Publisher
Packt
Pages
272
ISBN
9781847192561

 

Chapter 1. OOP vs. Procedural Programming

PHP is one of the most popular scripting languages of the last couple of years. Almost 60% of web servers are running on Apache with PHP. It is so popular that millions of websites and web applications are developed every month using PHP. PHP started its journey as a simple replacement for Perl, and in a few years it became tremendously popular and powerful. The language itself is closely similar to ANSI C.

One of the reasons why PHP became so popular is its short learning curve. Learning PHP is not a big job, especially if you are familiar with the syntax of Java or C. As writing PHP scripts is easy, anyone can write PHP code without following conventions and mixing presentation layers with business logics (which is one of the main reasons why there are large amounts of unmanageable projects floating around). Because there are no strict coding conventions followed in PHP, over the years as a project gets bigger, it can turn into an unmanageable demon.

OOP or Object Oriented Programming is a good programming practise to create manageable projects more easily. Procedural programming means writing code without objects. Procedural programming consists of codes with or without routines. OOP enlightens any language for better coding, for best performance and for writing very big projects without worrying a lot about managing them. OOP gives you facilities to create reusable objects that you or other developers can use in their projects without reinventing them again and again. OOP removes the hassles and difficulties of writing and managing big applications.

In this book we are going to discuss how you can achieve maximum benefits using OOP with PHP, using step-by-step instructions, real life examples how OOP helps you to write effective code, how to improve your coding style, and how to reuse them over time. This book won't work as a reference for PHP language; we will just cover OOP features of PHP and not the basics of general PHP. If you are looking for a good reference book, consult the PHP manual at first and then you can study Core PHP Programming, a very good book written by Leon Atkinson.

 

Introduction to PHP


This section is not for you if you are already a PHP developer, but for those who are new to PHP and starting with this book. Though I said at the very beginning that I assume you will have some pre development experience in PHP while reading this book, but if you are a total fresher and want to learn OOP with this book, this section may be worth recalling the basic PHP language features. If you are already familiar enough, don't skip this section as we have other topics to discuss here.

So you may ask where is the introduction to PHP, I am not seeing any code here! Well, you don't need to. The best resource on the internet is for free. Please go to http://www.php.net and download the manual and read the basic chapters. For a detailed learning of PHP, you can study the book Learning PHP5 written by David Sklar.

Ready, Set, Go

In this book, we are using PHP5.1.2 for our examples but for almost 99% of cases it will run with PHP version 5x. We have MySQL 5 in our machine and Apache 2 as our web server. If you aren't familiar with configuring all these in your machine, you can download pre configured WAMP or LAMP distributions like XAMPP (http://apachefriends.org) or Apache2Triad (http://www.apache2triad.net). You will find corresponding documentation for installation and customization on each of these product's website.

 

A Little History of OOP in PHP


When PHP was developed, it did not implement OO features in itself. After PHP/FI, when Zeev, Rasmus, and Andy rewrote the core and released PHP3, very basic OO features were introduced. When PHP4 was released, OO features got matured with huge performance improvement. But the PHP team rewrote the core engine again to introduce completely new object models and released PHP5. Now there are two versions of PHP being developed. Don't get confused by comparing PHP versions with other languages. PHP5 doesn't mean it is the latest PHP version. As I said a while ago, PHP4 and PHP5 are being released actively (though there will be no more releases of PHP4 after December 2007). Between these two, PHP5 implements almost complete OO features while PHP4 doesn't. At the time of writing this book the latest version of these two streams are PHP5.2 and PHP4.4.

 

Procedural vs. OO Coding Style


PHP allows you to write code in two flavours, one is procedural and the other is object oriented. You can even write procedural code in PHP5 and it will run without any problems. If you are not clear about procedural and object oriented programming, then we will have a look at these two different coding styles. The following two examples are not fully running examples rather a pseudo code:

<?
$user_input = $_POST[‘field‘];
$filtered_content = filter($user_input); //user input filtering
mysql_connect("dbhost","dbuser","dbpassword"); //database
mysql_select_db("dbname");
$sql = "some query";
$result = mysql_query($sql);
while ($data = mysql_fetch_assoc())
{
  process ($data);
}
process_user_input($filtered_content);
?>

You will notice using a lot of inline processing either directly or via using functions. It may stand as an example of typical procedural operation. Let's see how it looks after converting it to OOP:

<?
$input_filter = new filter();
$input_filter->filter_user_input(); //filter the user inputs
$db = new dal("mysql"); //data access layer
$db->connect($dbconfig);//we wre using mysql
$result = $db->execute($sql);
ReportGenerator::makereport($result); //process data
$model = new Postmodel($filter->get_filtered_content());
$model->insert();
?>

Now if you take a look into these two code snippets, you will find that the latter one is much more readable. Well, you can make the first one more readable by introducing some more functions into it, but how many functions are you ready to search into when you use them? The latter snippet is better organized because you know which object is handling which process. If you write big applications in procedural style, it will be almost impossible to manage after a few versions. Of course you can implement strict coding conventions, but it is agreed by millions of developers that it won't give you the ultimate manageability and usability if it's procedural unless you do it in OO style. Almost all big applications are written using the object oriented approach.

 

Benefits of OOP


OOP is invented to make the developer's life easier. Using OOP you can split your problems into smaller problems that are comparatively easy to comprehend. The main goal of OOP is: everything you want to do, do it via objects. Objects are basically small discrete pieces of code which, can incorporate data and behaviors together. In an application all these objects are connected to each other, they share data among them and solve problems.

OOP can be considered better from many aspects, especially when you consider the development time and maintenance overhead. The main benefits of OOP can be considered as follows:

  • Reusability: An object is an entity which has bundles of properties and methods and can interact with other objects. An object can be sufficient or it may have dependencies over other objects. But an object is usually developed to solve a specific set of problems. So when other developers suffer from the same set of problems, they can just incorporate your class to their project and use it without affecting their existing workflow. It prevents from DRY, which means Don't Repeat Yourself. In functional or modular programming, reusing is possible but complex.

  • Refactoring: When you need to refactor your projects, OOP gives you the maximum benefit because all objects are small entities and contain its properties and methods as a part of itself. So refactoring is comparatively easier.

  • Extensible: If you need to add features to your project, you can achieve best results from OOP. One of the core OOP features is extensibility. You can refactor your object to add the feature. While doing it, you can still maintain backward compatibility of this object so that it works fine with an old code base. Or you can extend the object and create a totally new object that retains all the necessary properties and methods of the parent object from which it has been derived, and then expose new features. This is termed "inheritance" and is a very important feature of OOP.

  • Maintenance: Object oriented code is easier to maintain because it follows somewhat strict coding conventions and is written in a self explanatory format. For example, when a developer extends it, refactors it, or debugs it, they can easily find out the inner coding structure and maintain the code time after time. Moreover, whenever there is a team development environment in your project, OOP could be the best solution because you can distribute your code after splitting it into small parts. These small parts could be developed as a separate object, so developers can develop them almost independently. Finally, it will be very easy to merge the code.

  • Efficiency: The concept of object oriented programming is actually developed for better efficiency and ease of development process. Several design patterns are developed to create better and efficient code. Moreover in OOP, you can think of your solution in a much better approach than procedural programming. Because you first split your problem into a small set of problems and then find solutions for each of them, the big problem is solved automatically.

 

Dissection of an Object


So what is an object? Well, it's nothing but a piece of code with a bunch of properties and methods. So is it similar to an array, as arrays can store data identified by properties (well, they are called keys)? Objects are much more than arrays because they contain some methods inside them. They can either hide them or expose them, which are not possible in arrays. The object is somewhat comparable with a data structure, data structure, and can incorporate a lot of other objects in itself and either creates a tight coupling among them or a loose one. And object can incorporate a lot of other object in itself and either creates a tight coupling among them or a loose one. We will learn more about loose coupling and tight coupling later in this book and understand how they will be useful for us.

Let's see the code of an object in PHP. The following object is a very simple object which can send email to a bunch of users. In PHP5, objects are a lot more different than an object in PHP4. We will not discuss the details of it, this is just an introductory object to see how the objects are written in PHP.

<?
//class.emailer.php
class emailer
{
  private $sender;
  private $recipients;
  private $subject;
  private $body;

  function __construct($sender)
  {
    $this->sender = $sender;
    $this->recipients = array();
  }
 
  public function addRecipients($recipient)
  {
    array_push($this->recipients, $recipient);
  }
  public function setSubject($subject)
  {
    $this->subject = $subject;
  }

  public function setBody($body)
  {
    $this->body = $body;
  }

  public function sendEmail()
  {
    foreach ($this->recipients as $recipient)
    {
      $result = mail($recipient, $this->subject, $this->body, 
                                "From: {$this->sender}\r\n");
      if ($result) echo "Mail successfully sent to 
                                         {$recipient}<br/>";
    }
  }
}
?>

The above object contains four private properties and three accessor methods and finally one more method to dispose the email to recipients. So how we are going to use it in our PHP code? Let's see below:

<?
$emailer = new emailer("[email protected]"); //construcion 
$emailer->addRecipients("[email protected]"); //accessing methods
// and passing some data
$emailer->setSubject("Just a Test");
$emailer->setBody("Hi Hasin, How are you?");
$emailer->sendEmail();
?>

I am sure that the above code snippet is much more self explanatory and readable. If you follow proper conventions, you can make your code easy to manage and maintain. Wordpress developers use a motto on their site www.wordpress.org which is "Coding is poetry". Coding is exactly a poem; if you just know how to write it.

 

Difference of OOP in PHP4 and PHP5


Objects in PHP5 differ a lot from objects in PHP4. OOP became matured enough in true sense from PHP5. OOP was introduced since PHP3 but that was just an illusion for real object oriented programming. In PHP4 you can create objects but you can't feel the real flavour of an object there. In PHP4 it was almost a poor object model.

One of the main differences of OOP in PHP4 is that everything is open; no restrictions about the usage of methods or properties. You can't use public, private, and protected modifiers for your methods. In PHP4 developers usually declare private methods with a double underscore. But it doesn't mean that declaring a method in that format actually prevents you from accessing that method outside the class. It's just a discipline followed.

In PHP4 you can find interfaces but no abstract or final keyword. An interface is a piece of code that any object can implement and that means the object must have all the methods declared in the interface. It strictly checks that you must implement all the functions in it. In the interface you can only declare the name and the access type of any method. An abstract class is where some methods may have some body too. Then any object can extend that abstract class and extend all these methods defined in that abstract class. A final class is an object which you are not allowed to extend. In PHP5 you can use all of these.

In PHP4 there are no multiple inheritances for interfaces. That means an interface can extend only one interface. But in PHP5 multiple inheritance is supported via implementing multiple interfaces together.

In PHP4, almost everything is static. That means if you declare any method in the class, you can call it directly without creating an instance of it. For example the following piece of code is valid in PHP4:

<?
class Abc
{
  var $ab;

  function abc()
  {
    $this->ab = 7;
  }
  function echosomething()
  {
    echo $this->ab;
  }
}

echo abc::echosomething();
?>

However it is not valid in PHP5 because the method echosomething() uses $this keyword which is not available in a static call.

There is no class-based constant in PHP4. There is no static property in objects in PHP4, and there is no destructor in PHP4 objects.

Whenever an object is copied, it is a shallow copy of that object. But in PHP5 shallow copy is possible only using the clone keyword.

There is no exception object in PHP4. But in PHP5 exception management is a great added feature.

There were some functions to investigate methods and properties of a class in PHP4, but in PHP5 beside those functions, a powerful set of API (Reflection API) is introduced for this purpose.

Method overloading via magic methods like __get() and __set() are available in PHP5. There are also lots of built-in objects to make your life easier.

But most of all, there is a huge performance improvement in PHP5 for OOP.

 

Some Basic OO Terms


Some of the basic object-oriented terms are as follows:

Class: A class is a template for an object. A class contains the code which defines how an object will behave and interact either with each other, or with it. Every time you create an object in PHP, you are actually developing the class. So sometimes in this book we will name an object as class, as they are both synonymous.

Property: A property is a container inside the class which can retain some information. Unlike other languages, PHP doesn't check the type of property variable. A property could be accessible only in class itself, by its subclass, or by everyone. In essence, a property is a variable which is declared inside the class itself, but not inside any function in that class.

Method: Methods are functions inside a class. Like properties, methods can also be accessible by those three types of users.

Encapsulation: Encapsulation is the mechanism that binds together code and the data it manipulates, and keeps both safe from outside interference and misuse. The wrapping up of data and methods into a single unit (called class) is known as encapsulation. The benefit of encapsulating is that it performs the task inside without making you worry.

Polymorphism: Objects could be of any type. A discrete object can have discrete properties and methods which work separately to other objects. However a set of objects could be derived from a parent object and retain some properties of the parent class. This process is called polymorphism. An object could be morphed into several other objects retaining some of its behaviour.

Inheritance: The key process of deriving a new object by extending another object is called inheritance. When you inherit an object from another object, the subclass (which inherits) derives all the properties and methods of the superclass (which is inherited). A subclass can then process each method of superclass anyway (which is called overriding).

Coupling: Coupling is the behaviour of how classes are dependent on each other. Loosely coupled architecture is much more reusable than tightly coupled objects. In the next chapter we will learn details about coupling. Coupling is a very important concern for designing better objects.

Design Patterns: First invented by the "Gang of Four", design patterns are just tricks in object oriented programming to solve similar sets of problems with a smarter approach. Using design patterns (DP) can increase the performance of your whole application with minimal code written by developers. Sometimes it is not possible to design optimized solutions without using DP. But unnecessary and unplanned use of DP can also degrade the performance of your application. We have a chapter devoted for design patterns in this book.

Subclass: A very common term in OOP, and we use this term throughout this book. When an object is derived from another object, the derived one is called the subclass of which it is derived from.

Superclass: A class is superclass to an object if that object is derived from it. To keep it simple, when you extend an object, the object which you are extending is the superclass of a newly extended object.

Instance: Whenever you create an object by calling its constructor, it will be called an instance. To simplify this, whenever you write some thing like this $var = new Object(); you actually create an instance of object class.

 

General Coding Conventions


We will be following some conventions in our codes throughout the book. Not being too strict, these conventions will help you to maintain your application at a large extent. Also, it will increase the maintainability of your code. It will also help you to write efficient code by avoiding duplicity and redundant objects. Last but not least, it will make your code much more readable.

  • In a single php file, we never write more than one class at a time. Out of the scope of that class, we will not write any procedural code.

  • We will save any class with a proper naming convention. For example we will save the file where we place the Emailer class introduced earlier in this chapter as class.emailer.php. What benefits can you achieve using this naming convention? Well, without going inside that file, you are now at least confirmed that this file contains a class named "Emailer".

  • Never mix the case in filenames. It creates ugly application structure. Go ahead with all small letters.

  • Like classes, we will save any interface as interface.name.php, Abstract class as abstract.name.php, and Final class as final.name.php.

  • We will always use Camel case while naming our classes. And that means the first letters of the major part is always a capital letter and the rest are small letter. For example a class named "arrayobject" will be more readable if we write ArrayObject.

  • While writing the name of properties or class variables, we will follow the same convention.

  • While writing the name of a method, we will start with a small letter and then the rest are camel case. For example, a method to send an email could be named as sendEmail.

  • Well, there is no more conventions used in this book.

 

Summary


In this chapter we learned about the object oriented programming and how it fits in with PHP. We have also learned some benefits over procedural and functional programming. However, we haven't gone through the details of OO language in PHP. In the next chapter we will learn more about objects and their methods and attributes, specifically creating objects, extending its features, and interacting between them. So, let our journey begin, Happy OOPing with PHP.

About the Author

  • Hasin Hayder

    Hasin Hayder graduated in Civil Engineering from the Rajshahi University of Engineering and Technology (RUET) in Bangladesh. He is a Zend-certified Engineer and expert in developing localized applications. He is currently working as a Technical Director in Trippert Labs and managing the local branch in Bangladesh. Beside his full time job, Hasin writes his blog at https://hasin.wordpress.com, writes article in different websites and maintains his open source framework, Orchid. Hasin lives in Bangladesh with his wife Ayesha and his son, Afif.

    Browse publications by this author

Latest Reviews

(2 reviews total)
Excelentes libros y con alto grado de profesionalidad
Nog niet aangevangen. .
Book Title
Access this book, plus 7,500 other titles for FREE
Access now