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:
o Public – the most visible. Methods can be read by everyone and properties can be written or read by anyone.
o Protected – the members are visible only by the actual class they are a part of, as well as by subclasses and parent classes.
o Private – members are visible only to the actual class they are a part of.
Here is an example of how members are declared
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”;
}
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.
o 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.
o 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.
o 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.
o 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
o 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:
o 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.
o As discussed above, objects are now passed by references. If you want to copy an object, make sure to use the clone keyword.
o 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.
o An object with no properties is no longer considered “empty”.
o 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.
Here are some differences I’ve run into during a recent php4 to php5 conversion:
Constructors (+1 for php5)
php4: Constructors are named after their class. If you change the name of a class, you have to find all callers of the constructors. Ew!
php5: Constructors are named __construct. If no __construct method is found, falls back to php4 behavior.
Destructors (+1 for php5)
php4: No such concept.
php5: Destructors are named __destruct.
$this = new Class(…); (+2 for php4)
php4: $this can be reassigned, allowing one to change the class implementing an object. A very useful feature and one I used quite a lot.
php5: Assignment to $this is explicitly forbidden. Factory methods are the recommended substitute, but they’re ugly.
array_shift($args = func_get_args()); (+1 for php4)
php4: If func_get_args() returns [a, b, c], $args is [b, c]–as expected.
php5: If func_get_args() returns [a, b, c], $args is [a, b, c]. Good luck hunting down that bug.
Copying through Assignment (+1 for php4)
$o1 = new Object(…); $o2 = $o1;
$o1->setThing(‘x’); $o2->setThing(‘y’);
php4: $o1 and $o2 are different objects, with Thing set to ‘x’ and ‘y’, respectively. This behavior matches that of strings, numbers, and other non-object types, which are also copied on assignment.
php5: $o1 and $o2 are the same object, with Thing set to ‘y’. This behavior contradicts that of strings, numbers, and other non-object types which do produce copies. A clone operator was introduced to work around this (provided your objects also implement __clone methods); however, the clone operator only works on objects, not strings or numbers, so ensuring you’ve produced a copy is now along the lines of $o2 = is_object($o1) ? clone $o1 : $o1;. Ick.
And some differences which might get used now that I’ve transitioned to php5:
Public, Protected, Private Class Variables (no point)
php4: All class variables are public.
php5: Class variables can have differing access levels. This annoys me, but some people like it.
Class Constants (+0.5 for php5)
php4: No such thing. I work around this, and the lack of namespacing in general, by using Class__CONSTANT.
php5: Has them as Class::CONSTANT. It isn’t namespace support, and has quite a few caveats, but it’s sort of an improvement if you squint just right.
Autoloading (+1 for php5)
php4: No such thing. If you want to load classes, you’d better make sure there are require_once statements all over the place. Or write an object-creation function (make_instance) which automatically loads any class that doesn’t exist. make_instance(‘Class’, …) isn’t nearly as pretty as new Class(…), though.
php5: Autoloading exists, provided you write an __autoload function. No more does require_once need to be littered around one’s code. A marginal savings overall, but still an improvement.