/Prototypal

Prototypal inheritance for PHP classes

Primary LanguagePHPOtherNOASSERTION

Prototypal

Version: 0.1.1-rc
Author: James Brumond

Copyright 2010 James Brumond
Dual licensed under MIT and GPL

Description

Prototypal inheritance for PHP classes

Basic Use

First, any class that you want to utilize prototyping must 1) extend the ProtoObject class (or a child of it) and 2) call the ProtoObject constructor (ProtoObject::__construct).

<?php

  class MyClass extends ProtoObject {
  
    public function __construct() {
      ProtoObject::__construct();
    }

  }

?>

Then, you can access the prototype chain either statically or through an instance of the class; however, if no instance has been created before you try to use prototyping statically, then you must first initialize the prototype chain by calling init_prototype():

<?php

  MyClass::init_prototype();

  MyClass::$prototype->one = 'foo';

  $my_object = new MyClass();

  echo $my_object->one;   // outputs: foo

  $my_object->prototype->one = 'bar';

  echo $my_object->one;   // outputs: bar

?>

Prototypes can be methods, as well. Every prototype method must have a first parameter (eg. $self) in order to access the object in question (much the same way python methods work).

<?php

  MyClass::$prototype->two = function($self) {
    echo $self->one;
  };
  
  $my_object->two();   // outputs bar

?>