Here are some major differences between PHP4 and PHP5 that you need to know:

1. Unified Constructors and Destructors:

In PHP4, constructors had same name as the class name. This used to cause overhead because every time you changed the class name, you had to change all the occurrences of that name.

In PHP5, you simply need to name your constructors as __construct(). (the word ‘construct’ prefixed by double underscores). Similarly you can name your destructors as __destruct(). (the word ‘destruct’ prefixed by double underscores.) In destructors, you can write code that will get executed when the object is destroyed.

2. Abstract Class:

PHP5 lets you declare a class as ‘Abstract’. (i.e. a class whose object cannot be created. You can only extend an abstract class) Also, a class must be defined as abstract if it contains any abstract methods. And those abstract methods must be defined within the class which extend that abstract class. You can include complete method definitions within the abstract methods of abstract class.

3. Final Keyword:

PHP5 allows you to declare a class or method as ‘Final’ now. You just need to use ‘final’ keyword that will indicate that the class cannot be inherited or the method cannot be overridden.

4. Exception Handling:

PHP5 has introduced ‘exceptions’. An exception is simply a kind of error and the ‘exception error’ can be handled in an exception object. By using an exception, one can gain more control over the simple trigger_error notices we were stuck with before.

When you are about to perform something ‘risky’ in your code, you can surround your code with a ‘try…catch’ block. First you surround your code in a ‘try {…….}’ block, then if an exception is thrown, your following ‘catch{……}’ block is there to intercept the error and handle it accordingly. You can write some PHP code in your ‘catch’ block which will get executed when an error occurs in the ‘try’ block. If there is no ‘catch’ block, a fatal error occurs.

PHP 5.5 and later, a finally block may also be specified after the catch blocks. Code within the finally block will always be executed after the try and catch blocks, regardless of whether an exception has been thrown, and before normal execution resumes.

The thrown object must be an instance of the Exception class or a subclass of Exception.
Example #2 Exception handling with a finally block
getMessage(), “\n”;
} finally {
echo “First finally.\n”;
}

try {
echo inverse(0) . “\n”;
} catch (Exception $e) {
echo ‘Caught exception: ‘, $e->getMessage(), “\n”;
} finally {
echo “Second finally.\n”;
}

// Continue execution
echo “Hello World\n”;
?>

The above example will output:
0.2
First finally.
Caught exception: Division by zero.
Second finally.
Hello World

5. E_STRICT Error Level:

PHP5 introduces new error level defined as ‘E_STRICT’ (value 2048). This error levels notifies you when you use depreciated PHP code. It is not included in E_ALL, if you wish to use this new level you must specify it explicitly.

6. Autoloading (the __autoload() function):

PHP5 introduces a special function called ‘__autoload()’ (the word ‘autoload’ prefixed by double underscores). This function allows you to avoid writing a long list of includes at the top of your script by defining them inside this function. So you can automatically load object files when PHP encounters a class that hasn’t been defined yet.

Example:

function __autoload ($class_name) {

include $class_name . ‘.php’;

}

7. Visibility:

In PHP5, class methods and properties now have ‘visibility’. There are 3 levels of visibilities:

Public: ‘Public’ is the most visible. Methods are accessible to everyone including objects outside the classes. And properties readable and writable by everyone including objects outside the classes.
Private: ‘Private’ makes class members only available to the class itself.
Protected: ‘Protected’ makes class members accessible to the class itself and any inherited class (subclass) as well as any parent classes.

PHP4′s method of declaring a variable as ‘var’ keyword is still supported in PHP5. The ‘var’ keyword is now a synonym for the ‘public’ keyword now.

8. Pass by Reference:

In PHP4, everything was passed by value, including objects. Whereas in PHP5, all objects are passed by reference. Take a look at this PHP4 code for example –

$peter = new Person();
$peter->sex = ’male’;

$maria = $peter;
$maria->sex = ’female’;

echo $peter->sex; // This will output ‘female’

As you can see in the code above, if you wanted to duplicate an object in PHP4, you simply copied it by assigning it to another variable (Pass by value). But now in PHP5 you must use the new ‘clone’ keyword. So the above PHP4 code, will now look like this in PHP5 –

$peter = new Person();
$maria = new Person();

$peter->sex = ’male’;

$maria = clone $peter;
$maria->sex = ’female’;

echo $peter->sex; // This will output ‘female’

9. Interfaces:

It’s also possible for interfaces to have constants.

PHP5 introduces ‘interfaces’ . An interface defines the methods a class must implement. All the methods defined in an interface must be public. An interface helps you design common APIs. It is not designed as a blueprint for classes, but just a way to standardize a common API. A big advantage of using interfaces is that a class can implement any number of interfaces. You can still only ‘extend’ on parent class, but you can ‘implement’ an unlimited number of interfaces.

10. Class Constants and Static Methods/Properties:
It is possible to define constant values on a per-class basis remaining the same and unchangeable. Constants differ from normal variables in that you don’t use the $ symbol to declare or use them.

The value must be a constant expression, not (for example) a variable, a property, a result of a mathematical operation, or a function call.
It’s also possible for interfaces to have constants.
As of PHP 5.3.0, it’s possible to reference the class using a variable. The variable’s value can not be a keyword (e.g. self, parent and static).

showConstant();

echo $class::CONSTANT.”\n”; // As of PHP 5.3.0
?>

Static methods and properties are also available. When you declare a class member as static, then it makes that member accessible (through the :: operator) without an instance. (Note this means within methods, the $this variable is not available).
For compatibility with PHP 4, if no visibility declaration is used, then the property or method will be treated as if it was declared as public.
Because static methods are callable without an instance of the object created, the pseudo-variable $this is not available inside the method declared as static.
Static properties cannot be accessed through the object using the arrow operator ->.

Calling non-static methods statically generates an E_STRICT level warning.

Like any other PHP static variable, static properties may only be initialized using a literal or constant; expressions are not allowed. So while you may initialize a static property to an integer or array (for instance), you may not initialize it to another variable, to a function return value, or to an object.

staticValue() . “\n”;
print $foo->my_static . “\n”; // Undefined “Property” my_static

print $foo::$my_static . “\n”;
$classname = ‘Foo’;
print $classname::$my_static . “\n”; // As of PHP 5.3.0

print Bar::$my_static . “\n”;
$bar = new Bar();
print $bar->fooStatic() . “\n”;
?>

11. Traits :
As of PHP 5.4.0, PHP implements a method of code reuse called Traits.
Traits are a mechanism for code reuse in single inheritance languages such as PHP. A Trait is intended to reduce some limitations of single inheritance by enabling a developer to reuse sets of methods freely in several independent classes living in different class hierarchies. The semantics of the combination of Traits and classes is defined in a way which reduces complexity, and avoids the typical problems associated with multiple inheritance and Mixins.

A Trait is similar to a class, but only intended to group functionality in a fine-grained and consistent way. It is not possible to instantiate a Trait on its own. It is an addition to traditional inheritance and enables horizontal composition of behavior; that is, the application of class members without requiring inheritance.

12. Type Hinting :

PHP 5 introduces type hinting. Functions are now able to force parameters to be objects (by specifying the name of the class in the function prototype), interfaces, arrays (since PHP 5.1) or callable (since PHP 5.4). However, if NULL is used as the default parameter value, it will be allowed as an argument for any later call.

If class or interface is specified as type hint then all its children or implementations are allowed too.

Type hints can not be used with scalar types such as int or string. Resources and Traits are not allowed either.

Example #1 Type Hinting examples
var;
}

/**
* Another test function
*
* First parameter must be an array
*/
public function test_array(array $input_array) {
print_r($input_array);
}

/**
* First parameter must be iterator
*/
public function test_interface(Traversable $iterator) {
echo get_class($iterator);
}

/**
* First parameter must be callable
*/
public function test_callable(callable $callback, $data) {
call_user_func($callback, $data);
}
}

// Another example class
class OtherClass {
public $var = ‘Hello World’;
}
?>

Failing to satisfy the type hint results in a catchable fatal error.
test(‘hello’);

// Fatal Error: Argument 1 must be an instance of OtherClass
$foo = new stdClass;
$myclass->test($foo);

// Fatal Error: Argument 1 must not be null
$myclass->test(null);

// Works: Prints Hello World
$myclass->test($otherclass);

// Fatal Error: Argument 1 must be an array
$myclass->test_array(‘a string’);

// Works: Prints the array
$myclass->test_array(array(‘a’, ‘b’, ‘c’));

// Works: Prints ArrayObject
$myclass->test_interface(new ArrayObject(array()));

// Works: Prints int(1)
$myclass->test_callable(‘var_dump’, 1);
?>

Type hinting also works with functions:
var;
}

// Works
$myclass = new MyClass;
myFunction($myclass);
?>

Type hinting allowing NULL value:

Advertisements