• Your Cart is Empty
  • Cart
  • Log In

PHP 4 and PHP 5 Comparison

Which PHP version to use? This is the question that we will try to answer in this article, presenting you with a detailed comparison between PHP 4 and PHP 5.

PHP, or Hypertext Preprocessor, has been the most used programming language for web pages for more than 8 years now, and for an industry, which is changing every few months, this is a really big achievement. In order to stay on top of things, the PHP Team is constantly working on improving the code in every way possible.

Currently, there are two PHP versions which are being used, PHP 4 and PHP 5. Even though PHP 4 is no longer developed, there are a lot of scripts still using this older version, due to its proven qualities.

At NTC Hosting, we believe in the power of choice. This is why we offer both the no longer developed PHP 4 and the currently supported version PHP 5, with all of our web hosting plans to form a powerful php hosting offer. Our clients can easily select the active PHP version for their account at any moment, and then can change it as many times as they want, using our user friendly PHP Settings Tool in the Web Hosting Control Panel.

And to assist in your choice, we will now take a closer look at the differences between the two most popular PHP versions.

The first thing that comes to mind when you start to compare PHP 4 and 5 is the:

Object Model

The Object Model was present in PHP 4, but it was completely reworked in PHP 5. Here are some of the most important updates:

  • Passed by Reference

    This is one of the most important innovations in PHP 5. In PHP 4 everything, including objects, was passed by value. This has been changed in PHP 5 where everything is passed by reference.
    PHP Code:

    $pObject1 = new Object();
    $pObject1->setName('Adam');
    $pObject1->setAddress('http://www.talkphp.com/');

    $pObject2 = new Object();
    $pObject2->setName('Karl');
    $pObject2->setAddress('http://www.talkphp.com/');

    This is a typical PHP 4 code - if you wanted to duplicate an object, you had to copy it and assign a new value to it. In PHP 5 the coder can simply use the "clone". This also means that you no longer need to use the reference operator (&) for your code.
    Here is how the same code will look in PHP 5 :

    $pObject1 = new Object();
    $pObject1->setName('Adam');
    $pObject1->setAddress('http://www.talkphp.com/');
    $pObject2 = clone $pObject1;
    $pObject2->setName('Karl');

    Since we were chaning only the name, we "cloned" the first object and simply changed the value that needed changing.

  • Class Constants and Static Methods/Properties

    With PHP 5 you can safely create class constants that act in very much the same way as do defined constants, but are limited within a class definition and can be accessed with "::". Have in mind that constants must have a constant expression for a value; they can't be equal to a variable or a result of a function call.
    Here is how you can define a constant:
    PHP Code:

    const constant = 'constant value';

    And here is how the constant can be accessed in a defined class:
    PHP Code:

    class MyClass
    {
       const constant = 'constant value';

       function showConstant() {
           echo  self::constant . "\n";
       }
    }

    The Static Methods and Properties are also a PHP 5 innovation. When a class member is declared as static, it's accessible with "::" without an instance.

  • Visibility

    In PHP 5 another addition is the "visibility" of the class methods and properties. The visibility has 3 levels:

    • Public - the most visible. Methods can be read by everyone and properties can be written or read by anyone.
    • Protected - the members are visible only by the actual class they are a part of, as well as by subclasses and parent classes.
    • Private - members are visible only to the actual class they are a part of.
    Here is an example of how members are declared <?php
    /*
    * Define ClassA
    */
    class ClassA
    {
    public $public = 'Public';
    protected $protected = 'Protected';
    private $private = 'Private';

    function printHello()
    {
    echo $this->public;
    echo $this->protected;
    echo $this->private;
    }
    }
    $bor = new ClassA();
    echo $bor->public; // Will work
    echo $bor->protected; // Will give you a fatal error
    echo $bor->private; // Will give you a fatal error
    $obj->printHello(); // Will display Public, Protected and Private

    /*
    * Define ClassB
    */
    class ClassB extends ClassA
    {
    // we can redeclare both the public and protected method, but we can't redeclare the private one
    protected $protected = 'Protected2';

    function printHello()
    {
    echo $this->public;
    echo $this->protected;
    echo $this->private;
    }
    }

    $obj2 = new MyClass2();
    echo $obj2->public; // Will work
    echo $obj2->private; // Is now undefined
    echo $obj2->protected; // Will display a fatal error
    $obj2->printHello(); // Will show you Public, Protected2, Undefined
    ?>
  • Unified Constructors and Destructors

    In PHP 4 the constructor was just a method with the same name as the name of the class. So, if you changed the name of the class, you had to go and update it every time it was used.

    In PHP 5, to spare the coders this hassle, the PHP developers have created an unified name for the constructors - "__construct()".

    A new addition is the "__destruct()" keyword. When used, the code will be executed only when the object is destroyed.

  • Abstract Classes

    With PHP 5 you can also create the so called "abstract" classes. These are classes, which are used only as a model to define other classes. If a certain class contains abstract method, it must be defined as abstract.

    Here is how a normal class is defined:

    class Message{

    and here is how an abstract class is defined:

    abstract class Message{
  • Interfaces

    Another new addition in PHP 5 is the "Interfaces", which can help you design an API. The interface will define the methods, which must be implemented in a class. Have in mind that all methods which are defined in an interface must be public.

    A big advantage of this new addition is that in a class you can implement any number of interfaces.
    Here is how it all works :

    an example of a simple class: class cow {
    function moo() {
    echo "moo, moo, moo...";
    }
    }
    and now we implement the interface in the class: class cow implements animal {
    function moo() {
    echo "moo, moo, moo...";
    }
    function breath() { echo "cow is breathing..."; }
    function eat() { echo "cow is easting..."; }
    }

    When an interface is implemented in a class, the class MUST define all methods and functions of the interface, otherwise the php parser will show a fatal error.

  • Magic Methods

    All methods, starting with a double underscore ("__") are defined as "Magic Methods". They are set to additional functionality to the classes. It's recommended that you don't use methods with the same naming pattern.

    Some of the most used magic methods are: __call, __get, __set and __toString.

  • Finality

    The "final" keyword has been introduced, so that a method cannot be overridden by a child now. This keyword can also be used to finalize a class in order to prevent it from having children.

  • The __autoload function

    A very useful function added in PHP 5, which can save the usage of several includes in the begging of the file. The __autoload function will load object files automatically when PHP encounters an undefined yet class.

    function __autoload($class_name) {
    require_once "./includes/classes/$class_name.inc.php";
    }

Besides the improvements to the object model, which we covered in the first part of this comparison , PHP 5 also introduces several completely new features

  • Introduction of Standard PHP Library (SPL)

    The Standard PHP Library (SPL) is a set of interfaces for PHP, whose aim is to implement more efficient data access interfaces and classes. This functionality is designed to ease the access to aggregate structures, such as arrays, database result sets, XML trees, directory listings or any other lists. At the moment, SPL works mainly with Iterators.

    The main benefit of this is that, since now it is set as Standard, it can be used by everybody to provide better coding practices.

  • Miscellaneous Features and Updates

    Here are the rest of the features, which do not fall into the previous categories.

    • Type Hinting

      Limited Type Hinting is introduced in PHP 5. Now the coder can select which kinds of variables can be passed to class methods or functions. For the moment, this feature works with classes or arrays only - integers and strings are not supported.

      function echo_user(User $user) {
      echo $user->getUsername();
      }

      A fatal error will appear if the passed parameter is not User or a subclass of User.

    • Exceptions

      Exceptions are finally added in PHP in the 5th revision of the programming language. While the exception is basically an error, by using it you can control the simple trigger_error notices, which were unchangeable in PHP 4.

      try {
      $cache->write();
      } catch (AccessDeniedException $e) {
      die('Unable to write the cache, access denied.');
      } catch (Exception $e) {
      die('Unknown error occurred : ' . $e->getMessage());
      }

      The exceptions are basically just objects. When an error occurs you can use an exception in its place. This way, when an exception is used, the rest of the following PHP code will not be executed.

      If you are about to do something, the result of which you are unsure, you can surround it with a "try" block and this way, if something happens, your catch block is there to catch the error message and handle it respectively.

    • E_STRICT Error Level

      In PHP 5 a new error lever is introduced - the E_STRICT error level. It's not included in E_ALL by default, so in order to use it, you will have to specify it. Its function is to notify you when deprecated code is used.

    • New Extensions

      Several new extensions are added in PHP 5. Among them, the most useful are:

      • SimpleXML - for an easier processing of XML data
      • DOM and XSL - their goal is to act in the place of DOMXML in PHP 4. With them, XML usage is much easier.
      • PDO - a very good OO interface for interacting with databases
      • Hash - you now have access to a lot of hash functions beside the most popular ones - md 5 and sha1
    • New Functions

      A lot of new functions are added to PHP 5. Here is a short list of the new additions:
      Arrays:

      • array_combine() - it will create one array, using another two arrays - one for the keys and one for their values
      • array_walk_recursive() - a user function is applied recursively to all of the array members

      InterBase:

      • ibase_db_info() - it will request the statistics for a database
      • ibase_name_result() - it will assign a name to a set of results
      • ibase_service_attach() - this function will connect you to the service manager
      • ibase_affected_rows() - it will return the number of rows affected by the previous query

      iconv:

      • iconv_strlen() - it will return the character count of a string
      • iconv_substr() - it will cut a part of a string
      • iconv_mime_decode_headers() - this function will decode several MIME headers at the same time

      Streams:

      • stream_copy_to_stream() - it will copy the data from one stream to another stream
      • stream_socket_get_name() - it will find the names of the local and remote sockets
      • stream_socket_sendto() - it will send a message to a socket, no matter if this socket is connected or not

      Date and time related:

      • date_sunset() - it will give you the time of the sunset for a given day and location
      • idate() - it will format the local time and date as an integer
      • date_sunrise() - it will give you the time of the sunrise for a given day and location

      Strings:

      • str_split() - it will convert a string to an array
      • strpbrk() - it will search the string for any set of characters specified

      For a full list of the new functions, you can visit the PHP Manual page

  • Compatibility Issues

    A section, which is vital to a lot of users. PHP 5, for the most part, is backwards compatible with PHP 4. However, there are some things that coders should bear in mind. Here is a set of the most commonly encountered issues:

    • array_merge() will now give you warnings if any of the parameters are not arrays. In PHP4, you could get away with merging non-arrays with arrays (and the items would just be added if they were say, a string). Of course it was bad practice to do this to begin with, but it can cause headaches if you don't know about it.
    • As discussed above, objects are now passed by references. If you want to copy an object, make sure to use the clone keyword.
    • get_*() now returns names as they were defined. If a class was called MyTestClass, then get_class() would return that -- case sensitive! In PHP4, they were always returned in lowercase.
    • An object with no properties is no longer considered "empty".
    • In some cases classes must be declared before use. It only happens if some of the new features of PHP 5 (such as interfaces) are used.

For a full list of the Backwards Compatibility Issues, you can also check the PHP Manual, which contains a lot of useful information on this subject.