Jump to content
Science Forums

Php


TINNY

Recommended Posts

The differentce between PHP4 and 5 is quite big.

Who better to explain it than php's creators...

By php.net

 

March 22, 2004

New Object Model

Private and Protected Members

Private and Protected Methods

Abstract Classes and Methods

Interfaces

Class Type Hints

final

Object Cloning

Unified Constructors

Destructors

Constants

Exceptions

Dereferencing Objects Returned from Functions

Static Member Variables of Static Classes Can Now be Initialized

Static Methods

instanceof

Static Function Variables

Parameters that are Passed by Reference to a Function May Now Have Default Values

__autoload()

Overloadable Method Calls and Property Accesses

Iteration

New __METHOD__ Constant

New __toString() Method

Reflection API

New Memory Manager

New Object Model

 

PHP's handling of objects has been completely rewritten, allowing for better performance and more features. In previous versions of PHP, objects were handled like primitive types (for instance integers and strings). The drawback of this method was that semantically the whole object was copied when a variable was assigned, or pass as a parameter to a method. In the new approach, objects are referenced by handle, and not by value (one can think of a handle as an object's identifier).

 

Many PHP programmers aren't even aware of the copying quirks of the old object model and, therefore, the majority of PHP applications will work out of the box, or with very few modifications.

Private and Protected Members

 

PHP 5 introduces private and protected member variables, they allow you to define the visibility of class properties.

Example

 

Protected member variables can be accessed in classes extending the class they are declared in, whereas private member variables can only be accessed by the class they belong to.

<?php
class MyClass {
  private $Hello = "Hello, World!n";
  protected $Bar = "Hello, Foo!n";
  protected $Foo = "Hello, Bar!n";

  function printHello() {
      print "MyClass::printHello() " . $this->Hello;
      print "MyClass::printHello() " . $this->Bar;
      print "MyClass::printHello() " . $this->Foo;
  }
}

class MyClass2 extends MyClass {
  protected $Foo;
          
  function printHello() {
      MyClass::printHello();                          /* Should print */
      print "MyClass2::printHello() " . $this->Hello; /* Shouldn't print out anything */
      print "MyClass2::printHello() " . $this->Bar;  /* Shouldn't print (not declared)*/
      print "MyClass2::printHello() " . $this->Foo;  /* Should print */
  }
}

$obj = new MyClass();
print $obj->Hello;  /* Shouldn't print out anything */
print $obj->Bar;    /* Shouldn't print out anything */
print $obj->Foo;    /* Shouldn't print out anything */
$obj->printHello(); /* Should print */

$obj = new MyClass2();
print $obj->Hello;  /* Shouldn't print out anything */
print $obj->Bar;    /* Shouldn't print out anything */
print $obj->Foo;    /* Shouldn't print out anything */
$obj->printHello();
?>

Private and Protected Methods

With PHP 5, private and protected methods are also introduced.

Example

<?php
class Foo {
  private function aPrivateMethod() {
      echo "Foo::aPrivateMethod() called.n";
  }

  protected function aProtectedMethod() {
      echo "Foo::aProtectedMethod() called.n";
      $this->aPrivateMethod();
  }
}

class Bar extends Foo {
  public function aPublicMethod() {
      echo "Bar::aPublicMethod() called.n";
      $this->aProtectedMethod();
  }
}

$o = new Bar;
$o->aPublicMethod();
?>

Old code that has no user-defined classes or functions named "public", "protected" or "private" should run without modifications.

Abstract Classes and Methods

 

PHP 5 also introduces abstract classes and methods. An abstract method only declares the method's signature and does not provide an implementation. A class that contains abstract methods needs to be declared abstract.

Example

<?php
abstract class AbstractClass {
  abstract public function test();
}

class ImplementedClass extends AbstractClass {
  public function test() {
      echo "ImplementedClass::test() called.n";
  }
}

$o = new ImplementedClass;
$o->test();
?>

Abstract classes cannot be instantiated. Old code that has no user-defined classes or functions named 'abstract' should run without modifications.

Interfaces

 

PHP 5 introduces interfaces. A class may implement an arbitrary list of interfaces.

Example

<?php
interface Throwable {
  public function getMessage();
}

class MyException implements Throwable {
  public function getMessage() {
      // ...
  }
}
?>

Old code that has no user-defined classes or functions named 'interface' or 'implements' should run without modifications.

Class Type Hints

 

While remaining loosely typed PHP 5 introduces the ability to use class type hints to declare the expected class of objects that are passed as parameters to a method.

Example

<?php
interface Foo {
  function a(Foo $foo);
}

interface Bar {
  function b(Bar $bar);
}

class FooBar implements Foo, Bar {
  function a(Foo $foo) {
      // ...
  }

  function b(Bar $bar) {
      // ...
  }
}

$a = new FooBar;
$b = new FooBar;

$a->a($:);
$a->b($:);
?>

These class type hints are not checked upon compilation, as would be the case in a typed language, but during runtime. This means that:

<?php
function foo(ClassName $object) {
  // ...
}
?>

is equivalent to:

<?php
function foo($object) {
  if (!($object instanceof ClassName)) {
      die("Argument 1 must be an instance of ClassName");
  }
}
?>

This syntax only applies to objects/classes, not built-in types.

final

 

PHP 5 introduces the "final" keyword to declare final members and methods. Methods and members declared final cannot be overridden by sub-classes.

Example

<?php
class Foo {
  final function bar() {
      // ...
  }
}
?>

It is furthermore possible to make a class final. Doing this prevents a class from being specialized (it cannot be inherited by another class). There's no need to declare the methods of a final class themselves as final.

Example

<?php
final class Foo {
  // class definition
}

// the next line is impossible
// class Bork extends Foo {}
?>

Properties cannot be final.

 

Old code that has no user-defined classes or functions named 'final' should run without modifications.

Object Cloning

 

PHP 4 offered no way a user could decide what copy constructor to run when an object is duplicated. During duplication, PHP 4 did a bit for bit copy making an identical replica of all the object's properties.

 

Creating a copy of an object with fully replicated properties is not always the wanted behavior. A good example of the need for copy constructors, is if you have an object which represents a GTK window and the object holds the resource of this GTK window, when you create a duplicate you might want to create a new window with the same properties and have the new object hold the resource of the new window. Another example is if your object holds a reference to another object which it uses and when you replicate the parent object you want to create a new instance of this other object so that the replica has its own separate copy.

 

An object copy is created by calling the object's __clone() method:

<?php
$copy_of_object = $object->__clone();
?>

When the developer asks to create a new copy of an object, PHP 5 will check if a __clone() method has been defined or not. If not, it will call a default __clone() which will copy all of the object's properties. If a __clone() method is defined, then it will be responsible to set the necessary properties in the created object. For convenience, the engine will supply a function that imports all of the properties from the source object, so that they can start with a by-value replica of the source object, and only override properties that need to be changed.

Example

<?php
class MyCloneable {
  static $id = 0;

  function MyCloneable() {
      $this->id = self::$id++;
  }

  function __clone() {
      $this->name = $that->name;
      $this->address = "New York";
      $this->id = self::$id++;
  }
}

$obj = new MyCloneable();

$obj->name = "Hello";
$obj->address = "Tel-Aviv";

print $obj->id . "n";

$obj = $obj->__clone();

print $obj->id . "n";
print $obj->name . "n";
print $obj->address . "n";
?>

Unified Constructors

 

PHP 5 allows developers to declare constructor methods for classes. Classes which have a constructor method call this method on each newly-created object, so it is suitable for any initialization that the object may need before it is used.

 

With PHP 4, constructor methods were class methods that had the same name as the class itself. Since it is very common to call parent constructors from derived classes, the way PHP 4 worked made it a bit cumbersome to move classes around in a large class hierarchy. If a class is moved to reside under a different parent, the constructor name of that parent changes as well, and the code in the derived class that calls the parent constructor has to be modified.

 

PHP 5 introduces a standard way of declaring constructor methods by calling them by the name __construct().

Example

<?php
class BaseClass {
  function __construct() {
      print "In BaseClass constructorn";
  }
}

class SubClass extends BaseClass {
  function __construct() {
      parent::__construct();
      print "In SubClass constructorn";
  }
}

$obj = new BaseClass();
$obj = new SubClass();
?>

For backwards compatibility, if PHP 5 cannot find a __construct() function for a given class, it will search for the old-style constructor function, by the name of the class. Effectively, it means that the only case that would have compatibility issues is if the class had a method named __construct() which was used for different semantics.

Destructors

 

Having the ability to define destructors for objects can be very useful. Destructors can log messages for debugging, close database connections and do other clean-up work. No mechanism for object destructors existed in PHP 4, although PHP had already support for registering functions which should be run on request shutdown.

 

PHP 5 introduces a destructor concept similar to that of other object-oriented languages, such as Java: When the last reference to an object is destroyed the object's destructor, which is a class method named __destruct() that receives no parameters, is called before the object is freed from memory.

Example

<?php
class MyDestructableClass {
  function __construct() {
      print "In constructorn";
      $this->name = "MyDestructableClass";
  }

  function __destruct() {
      print "Destroying " . $this->name . "n";
  }
}

$obj = new MyDestructableClass();
?>

Like constructors, parent destructors will not be called implicitly by the engine. In order to run a parent destructor, one would have to explicitly call parent::__destruct() in the destructor body.

Constants

 

PHP 5 introduces per-class constants:

<?php
class Foo {
  const constant = "constant";
}

echo "Foo::constant = " . Foo::constant . "n";
?>

Old code that has no user-defined classes or functions named 'const' will run without modifications.

Exceptions

 

PHP 4 had no exception handling. PHP 5 introduces a exception model similar to that of other programming languages. Note that there is support for "catch all" but not for the "finally" clause.

 

Exceptions can be rethrown in catch blocks. Also it is possible to have multiple catch blocks. In that case the caught exception is compared with the classtype of each catch block from top to bottom and the first block that has an 'instanceof' match gets executed. When the catch block finishes, execution continues at the end of the last catch block. If no catch block has an 'instanceof' match then the next try/catch block is searched until no more try/catch blocks are available. In that case the exception is an uncaught exception and the program terminates with showing the exception.

Example

<?php
class MyException {
  function __construct($exception) {
      $this->exception = $exception;
  }

  function Display() {
      print "MyException: $this->exceptionn";
  }
}

class MyExceptionFoo extends MyException {
  function __construct($exception) {
      $this->exception = $exception;
  }

  function Display() {
      print "MyException: $this->exceptionn";
  }
}

try {
  throw new MyExceptionFoo('Hello');
}
catch (MyException $exception) {
  $exception->Display();
}
catch (Exception $exception) {
  echo $exception;
}
?>

Even though the above example shows that it is possible to define exception classes that don't inherit from Exception it is best to do so. This is because the internal Exception class can gather a lot of information otherwise not available. The PHP code emulation code would look something like shown below. The comments show the meaning of each property and hence their getter methods. As the code shows it is possible to read any available information by using the getter methods. But since some of the methods are used internally they are marked final. All in all the class is very restrictive because it must be ensured that anything used internally always works as expected.

Example

<?php
class Exception {
  function __construct(string $message=NULL, int code=0) {
      if (func_num_args()) {
          $this->message = $message;
      }
      $this->code = $code;
      $this->file = __FILE__; // of throw clause
      $this->line = __LINE__; // of throw clause
      $this->trace = debug_backtrace();
      $this->string = StringFormat($this);
  }

  protected $message = 'Unknown exception';  // exception message
  protected $code = 0; // user defined exception code
  protected $file;    // source filename of exception
  protected $line;    // source line of exception

  private $trace;      // backtrace of exception
  private $string;    // internal only!!

  final function getMessage() {
      return $this->message;
  }
  final function getCode() {
      return $this->code;
  }
  final function getFile() {
      return $this->file;
  }
  final function getTrace() {
      return $this->trace;
  }
  final function getTraceAsString() {
      return self::TraceFormat($this);
  }
  function _toString() {
      return $this->string;
  }
  static private function StringFormat(Exception $exception) {
      // ... a function not available in PHP scripts
      // that returns all relevant information as a string
  }
  static private function TraceFormat(Exception $exception) {
      // ... a function not available in PHP scripts
      // that returns the backtrace as a string
  }
}
?>

If you derive your exception classes from this Exception base class your exceptions will be nicely shown in the built-in handler for uncaught exceptions.

 

Old code that has no user-defined classes or functions 'catch', 'throw' and 'try' will run without modifications.

Dereferencing Objects Returned from Functions

 

In PHP 4 it wasn't possible to dereference objects returned by functions and make further method calls on those objects. With PHP 5, the following is now possible:

<?php
class Circle {
  function draw() {
      print "Circlen";
  }
}
      
class Square {
  function draw() {
      print "Squaren";
  }
}

function ShapeFactoryMethod($shape) {
  switch ($shape) {
      case "Circle":
          return new Circle();
      case "Square":
          return new Square();
  }
}

ShapeFactoryMethod("Circle")->draw();
ShapeFactoryMethod("Square")->draw();
?>

Static Member Variables of Static Classes Can Now be Initialized

Example

<?php
class foo {
  static $my_static = 5;
  public $my_prop = 'bla';
}

print foo::$my_static;
$obj = new foo;
print $obj->my_prop;
?>

Static Methods

 

PHP 5 introduces the 'static' keyword to declare a method static, thus callable from outside the object context.

Example

<?php
class Foo {
  public static function aStaticMethod() {
      // ...
  }
}

Foo::aStaticMethod();
?>

The pseudo variable $this is not available inside a method that has been declared static.

instanceof

 

PHP 5 introduces the instanceof keyword, that allows you to ascertain whether or not an object is an instance of a class, or extends a class, or implements an interface.

Example

<?php
class baseClass { }

$a = new baseClass;

if ($a instanceof baseClass) {
  echo "Hello World";
}
?>

Static Function Variables

 

Statics are now treated at compile-time which allows developers to assign variables to statics by reference. This change also greatly improves their performance but means that indirect references to statics will not work anymore.

Parameters that are Passed by Reference to a Function May Now Have Default Values

Example

<?php
function my_function(&$var = null) {
  if ($var === null) {
      die("$var needs to have a value");
  }
}
?>

__autoload()

 

The __autoload() interceptor function will be automatically called when an undeclared class is to be instantiated. The name of that class will be passed to the __autoload() interceptor function as its only argument.

Example

<?php
function __autoload($className) {
  include_once $className . ".php";
}

$object = new ClassName;
?>

Overloadable Method Calls and Property Accesses

 

Both method calls and property accesses can be overloaded via the __call(), __get() and __set() methods.

Example: __get() and __set()

<?php
class Setter {
  public $n;
  public $x = array("a" => 1, "b" => 2, "c" => 3);

  function __get($nm) {
      print "Getting [$nm]n";

      if (isset($this->x[$nm])) {
          $r = $this->x[$nm];
          print "Returning: $rn";
          return $r;
      } else {
          print "Nothing!n";
      }
  }

  function __set($nm, $val) {
      print "Setting [$nm] to $valn";

      if (isset($this->x[$nm])) {
          $this->x[$nm] = $val;
          print "OK!n";
      } else {
          print "Not OK!n";
      }
  }
}

$foo = new Setter();
$foo->n = 1;
$foo->a = 100;
$foo->a++;
$foo->z++;
var_dump($foo);
?>

Example

: __call()

<?php
class Caller {
  var $x = array(1, 2, 3);

  function __call($m, $a) {
      print "Method $m called:n";
      var_dump($a);
      return $this->x;
  }
}

$foo = new Caller();
$a = $foo->test(1, "2", 3.4, true);
var_dump($a);
?>

Iteration

 

Objects may be iterated in an overloaded way when used with foreach. The default behavior is to iterate over all properties.

Example

<?php
class Foo {
  var $x = 1;
  var $y = 2;
}

$obj = new Foo;

foreach ($obj as $prp_name => $prop_value) {
  // using the property
}
?>

Each class whose instances can be iterated with foreach should implement the empty interface Traversable. Hence any object that says it implements Traversable can be used with foreach.

 

The interfaces IteratorAggregate and Iterator allows you to specify how class objects are iterated in PHP code. The first of them simply has a method getIterator() which must return an array or an object that either implements the interface Iterator or is instantiated from an internal class that can be iterated.

Example

<?php
class ObjectIterator implements Iterator {

  private $obj;
  private $num;

  function __construct($obj) {
      $this->obj = $obj;
  }
  function rewind() {
      $this->num = 0;
  }
  function hasMore() {
      return $this->num < $this->obj->max;
  }
  function key() {
      return $this->num;
  }
  function current() {
      switch($this->num) {
          case 0: return "1st";
          case 1: return "2nd";
          case 2: return "3rd";
          default: return $this->num."th";
      }
  }
  function next() {
      $this->num++;
  }
}

class Object implements IteratorAggregate {

  public $max = 3;

  function getIterator() {
      return new ObjectIterator($this);
  }
}

$obj = new Object;

// this foreach ...
foreach($obj as $key => $val) {
  echo "$key = $valn";
}

// matches the following 7 lines with the for directive.
$it = $obj->getIterator();
for($it->rewind(); $it->hasMore(); $it->next) {
  $key = $it->current();
  $val = $it->key();
  echo "$key = $valn";
}
unset($it);
?>

The matching for directive is very interesting here since it shows the use of all abstract methods declared in the interfaces Iterator and IteratorAggregate respectively.

New __METHOD__ Constant

 

The new __METHOD__ pseudo constant shows the current class and method when used inside a method and the function when used outside of a class.

Example

<?php
class Foo {
  function Show() {
      echo __FILE__ . '(' . __LINE__ . ')' . __METHOD__;
  }
}
function Test() {
  echo __FILE__ . '(' . __LINE__ . ')' . __METHOD__;
}
?>

New __toString() Method

 

The new __toString() magic method allows you to overload the object to string conversion.

Example

<?php
class Foo {
  function __toString() {
      return "What ever";
  }
}

$obj = Foo;

$str = (string) $obj; // call __toString()

echo $obj; // call __toString()
?>

Reflection API

 

PHP 5 comes with a complete reflection API that adds the ability to reverse-engineer classes, interfaces, functions and methods as well as extensions.

 

The reflection API also offers ways of getting doc comments for functions, classes and methods.

 

Nearly all aspects of object oriented code can be reflected by using the reflection API which is documented separately.

Example

<?php
class Foo {
  public $prop;
  function Func($name) {
      echo "Hello $name";
  }
}

reflection_class::export('Foo');
reflection_object::export(new Foo);
reflection_method::export('Foo', 'func');
reflection_property::export('Foo', 'prop');
reflection_extension::export('standard');
?>

New Memory Manager

 

PHP 5 has a new memory manager which allows it to run efficiently in multi-threaded environments as it doesn't need to use mutexes to lock and unlock during allocation/deallocation.

 

and here is how OO support in PHP evolve article:

By Zeev Suraski

 

March 16, 2004

 

Where did it all start?

Objects in the old days

The limitations of the old Object Model

The Answer – Zend Engine 2

What does that mean to end-users?

What else is new?

Conclusion

About the Author

 

 

One of the key ingredients in the upcoming version 5 of PHP is going to be the Zend Engine 2.0, with support for a brand new object oriented programming model. This article describes the evolution of the object oriented programming support in PHP, and covers the new features and changes that are scheduled for PHP 5.

Where did it all start?

 

Not too many people know this, but when PHP as we know it today was being molded, back in the summer of 1997, there weren’t any plans for it to have any object-oriented capabilities. As a matter of fact, it got pretty far without having any notion of classes or objects – it was to be a purely structured language. One of these summer nights however, on August 27th, this changed.

 

At the time classes were introduced to the source tree of what was to become PHP 3.0, they were added as syntactic sugar for accessing collections. PHP already had the notion of associative arrays collections, and the new critters were nothing but a neat new way of accessing them. However, as time has proven, this new syntax proved to have a much more far-reaching effect on PHP than was originally intended.

 

Another thing that most people don’t know, is that by the time PHP 3.0 came out officially, mid 1998, and was gaining momentum at a staggering rate, Andi Gutmans and I were already determined to rewrite the language implementation. Users may have liked it, in fact we know they did, but as the authors of the engine, we knew what was going on under the hood and we couldn’t live at peace with that. The rewrite, which was later dubbed ‘Zend Engine’ (Zend being a combination of Zeev and Andi), was both the trigger for and one of the core components in the 2nd revolution PHP went through in just over a year.

 

This revolution, however, left PHP’s object model mostly unchanged from version 3 – it was still very simple. Objects were still very much syntactic sugar for associative arrays, and didn’t offer users too many features on top of that.

Objects in the old days

 

So, what could you do with objects back in the PHP 3.0 and for that matter, the current PHP 4.0 days? Not that much. Objects were essentially containers of properties, like associative arrays. The biggest difference was that objects had to belong to a class. Classes, like in other languages, contained a collection of properties and methods (functions), and objects could be instantiated from them using the new operator. Single inheritance was supported, allowing users to extend (or specialize) the scope of an existing class without having to write it from scratch or copy it. Finally, PHP 4.0 also added the ability to call methods of a specific class, from both within and outside object contexts.

 

One of the biggest twists in PHP’s history was the fact that despite the very limited functionality, and despite a host of problems and limitations, object oriented programming in PHP thrived, and became the most popular paradigm for the growing numbers of off-the-shelf PHP applications. This trend, which was mostly unexpected, caught PHP in a sub-optimal situation. The fact that objects were not behaving like objects in other OO languages, and were instead behaving like associating arrays was beginning to show.

The limitations of the old Object Model

 

The most problematic aspects of the PHP 3 / PHP 4 object model was the fact that objects were passed around by value, and not by reference. What does that mean?

 

Let’s say you have a simple, somewhat useless function, called myFunction():

function myFunction($arg)
{
   $arg = 5;
}

And you call this function:

$myArgument = 7;
myFunction($myArgument);
print $myArgument;

As you probably know, the call to myFunction() will leave $myArgument unchanged; What is sent to myFunction() is a copy of $myargument’s value, and not $myargument itself. This type of argument passing is called passing arguments by value. Passing arguments by reference is done by most structured languages, and is extremely useful, as it allows you to write your functions, or call other people’s functions without worrying about side effects they may have variables outside their scope.

 

However, consider the following example:

function wed($bride, $groom)
{
   if ($bride->setHusband($groom)&& $groom->setWife($bride)) {
       return true;
   } else {
       return false;
   }
}

wed($joanne, $joe);
print areMarried($joanne, $joe);

(The implementation of Woman::setHusband, Man::setWife() and areMarried() is left as an exercise for the reader).

 

What will areMarried() return? We would hope that the two newlyweds would manage to stay married at least until the following line of code, but as you may have guessed – they wouldn’t. areMarried() will confirm that they got divorced just as soon as they got married. Why?

 

The reason is simple. Because objects in PHP 3.0 and 4.0 are not ‘special’, and behave like any other kind of variable, when you pass $joanne ane $joe to wed(), you don’t really pass them. Instead, you pass clones or replicas of them. So, while their clones end up being married inside wed(), the real $joe and $joanne remain within a safe distance from the sacrament of holy matrimony, in their protected outer-scope.

 

Of course, PHP 3 and 4 did give you an option to force your variables be passed by reference, consequently allowing functions to change the arguments that were passed to them in the outer scope. If we defined wed()’s prototype like this:

function wed(&$bride, &$groom)

then Joanne and Joe would have had better luck (or not, depending on your point of view).

 

However, it gets more complicated than that. For instance, what if you want to return an object from a function, by reference? What if you want to make modifications to $this inside the constructor, without worrying about what may happen when it gets copied back from new’s result into the container variable[#]?

 

While PHP 3 and 4 did address these problems to a certain extent by providing syntactic hacks to pass around objects by reference, they never addressed the core of the problem:

 

Objects and other types of values are not created equal,

 

Therefore,

 

Objects should be passed around by reference unless stated otherwise.

The Answer – Zend Engine 2

 

When we were finally convinced that objects are indeed special creatures, and deserve their own distinct behavior, it was only the first step. We had to come up with a way of doing this without interfering with the rest of the semantics of PHP, and preferably, without having to rewrite the whole of PHP itself. Luckily, the solution came in the form of a big light bulb that emerged above the head of Andi Gutmans, just over a year ago. His idea was to replace objects with object handles. The object handles would be essentially numbers, indices in a global object table. Much like any other kind of variables, they will be passed and returned by value. However, thanks to this new level of indirection, since we will be now moving around handles to the objects, and not the objects themselves, effectively – PHP will behave as if the objects themselves are passed by reference.

 

Let’s go back to Joe and Joanne. How would wed() behave differently now? First off, $joanne and $joe will no longer be objects, but rather, object handles, let’s say 4 and 7 respectively. These integer handles point to slots in some global objects table where the actual objects sit. When we send them to wed(), the local variables $bride and $groom will receive the values 4 and 7; setHusband() will change the object referenced by 4; setWife() will change the object referenced by 7; and when wed() returns, $joanne and $joe will already be living the first day of the rest of their lives together.

What does that mean to end-users?

 

Alright, so the ending to the story is now more idyllic, but what does it mean to PHP developers? Quite a few things. First, it means that your applications will run faster, as there will be much less data-copying going around. For instance, when you send $joe to a function, instead of having to create a replica, and copy over his name, birth date, parents’ name, list of former addresses, social security number and whatnot – PHP will only have to pass on one object handle, one integer. Of course, a direct result of this is also a significant amount of memory savings – storing an integer takes much less space than storing a full-fledged replica of the object.

 

But perhaps more importantly, the new object model makes object oriented programming in PHP much more powerful and intuitive. No longer will you have to mess up with cryptic & signs in order to get the job done. No longer will you have to worry about whether changes you make to the object inside the constructor will survive the dreaded new-operator behavior. No longer will you ever have to stay up until 2:00am tracking elusive bugs! Ok, maybe I’m lying with that last one, but seriously, the new object model reduces the object-related stay-up-until-2:00am type of bugs very significantly. In turn, it means that the feasibility of using PHP for large scale projects becomes much more easy to explain.

What else is new?

 

As one could expect, the Zend Engine 2 packs quite a few other features to go along with its brand new object model. Some of them further enhance object-oriented features, like private member variables and methods, static variables and language-level aggregation. Most notable is the revolutionized interaction with external component models, such as Java, COM/DCOM and .NET through overloading; In comparison to PHP 4.0, which first introduced this sort of integration, the new implementation is quicker (by a wide margin), more complete, more reliable and even easier to maintain and extend. This means that PHP 5.0 will play very nicely in your existing Java or .NET based setup, and you will be able to use your existing components inside PHP, transparently, as if they were regular PHP objects. Unlike PHP 4.0 which had a special implementation for such overloaded objects, in the Zend Engine 2 / PHP 5.0 – all objects use the same interface, including the built-in PHP objects. This ensures that PHP objects and overloaded objects behave in exactly the same way.

 

Finally, the Zend Engine 2 also brings exception handling to PHP. The sad reality is that most developers, to date, write code which does not handle error situations gracefully. It’s not uncommon to see sites that spit out cryptic database errors to your browser, instead of displaying a well-phrased ‘An error has occurred’ kind of message. With PHP, the key reason for this is that handling error situations is a daunting task – you actually have to check for the return value of each and every function. Since set_error_handler() was added, things became slightly better, as it became possible to centralize error handling – but it still left a lot to be desired. The addition of exception handling to PHP will allow developers both fine-grained error recovery, but perhaps more importantly, graceful application-wide error recovery.

Conclusion

 

The release of PHP 5.0, powered by the Zend Engine 2.0, will mark a significant step forward in PHP’s evolution as one of the key Web platforms in the world today. While keeping its firm commitment to users who prefer using the functional structured syntax of PHP, it will make a giant leap for those who are interested in its object oriented capabilities, and especially the companies developing large scale applications.

About the Author

 

Zeev has been working for over five years on the PHP project. Along with Andi Gutmans, he started the PHP 3 and 4 projects and wrote most of their infrastructure and core components, thereby helping to forge PHP as we know it today and attracting many more developers to join in. Zeev is a co-founder of Zend Technologies Ltd, the leading provider of development and performance management tools for PHP-enabled enterprises, and serves as a CTO for the company. Zend’s website is http://www.zend.com.

 

Hope this helps!

Link to comment
Share on other sites

Hope this helps

sure does! especially helpful for someone who hardly knows php at all. I've only a rudimentary experience of asp as background knowledge.

what was actually at the back of my mind was whether it'd be better to learn 5 or 4. of course 5 is the latest and most powerful, but not have many resources and code libraries available. and the website right now uses 4. what changes have to be made to switch to 5?

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
×
×
  • Create New...