Example 1: A singleton (static members) ======================================= counter; print "\n"; } } class SingletonCounter { static $m_instance = NULL; function Instance() { if (self::$m_instance == NULL) { self::$m_instance = new Counter(); } return self::$m_instance; } } SingletonCounter::Instance()->increment_and_print(); SingletonCounter::Instance()->increment_and_print(); SingletonCounter::Instance()->increment_and_print(); ?> Example 2: Factory method (derefencing objects returned from functions) ======================================================================= draw(); ShapeFactoryMethod("Square")->draw(); ?> Example 3: Class constants and class scope ========================================== Example 4: Regular object method using both local and global functions ====================================================================== get_hello_world(); return strlen($str); } } $obj = new HelloWorld(); print "length_of_hello_world() = " . $obj->length_of_hello_world(); print "\n"; ?> Example 5: Multiple derefencing of objects returned from methods ================================================================ name = $_name; } function display() { print $this->name; print "\n"; } } class Person { function Person($_name, $_address) { $this->name = new Name($_name); } function getName() { return $this->name; } } $person = new Person("John", "New York"); $person->getName()->display(); ?> Example 6: Exception handling ============================= error = $_error; } function getException() { return $this->error; } } function ThrowException() { throw new MyException("'This is an exception!'"); } try { } catch (MyException $exception) { print "There was an exception: " . $exception->getException(); print "\n"; } try { ThrowException(); } catch (MyException $exception) { print "There was an exception: " . $exception->getException(); print "\n"; } ?> Example 7: __clone() =================== 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; print "\n"; $obj = $obj->__clone(); print $obj->id; print "\n"; print $obj->name; print "\n"; print $obj->address; print "\n"; ?> Example 8: Unified constructors =============================== Example 9: Destructors ======================= name = "MyDestructableClass"; } function __destruct() { print "Destroying " . $this->name . "\n"; } } $obj = new MyDestructableClass(); ?>