ClassPrototype Version 1.0

Introduction

Class prototype can be used to implement a simple version of the prototype pattern, similar to the Javascript implementation.

Usage

All yuo need to do to build the prototype of a class is to extend the classPrototype class and make sure that its __construct() will be called.
							include "classPrototype.php";
							
							class test extends classPrototype
							{
								function __construct()
								{
									//The __construct method has been replaced, but you can call it in this way
									parent::__construct();
								}
							}

							$test=new test();
							//In this way you can access the prototype object
							$test->prototype;
						
After that every instance of the class will get the prototype property.
If you assign a new property on the prototype object, every instance of the class will be updated and the new instances will get that property too.
							include "classPrototype.php";
							
							class test extends classPrototype
							{
								function __construct()
								{
									parent::__construct();
								}
							}
							
							//Create two instances of the test class
							$test=new test();
							$foo=new test();
							
							//Assign the "variable" property. $test and $foo will get this property.
							$test->prototype->variable="ok";
							
							//Also this new instance will get it.
							$bar=new test();
							
							echo $test->variable; //Prints: "ok"
							echo $foo->variable; //Prints: "ok"
							echo $bar->variable; //Prints: "ok"
						
The properties cannot be updated if they already exists on the instance, but the prototype object will be updated anyway so new instances will have the updated value for those properties.
							include "classPrototype.php";
							
							class test extends classPrototype
							{
								var $variable=3;
							}
							
							//Create an instance of the class. 
							//At this point the "variable" property has value 3 in the prototype
							$test=new test();
							
							//Update the prototype. $test won't be updated because the "variable" property is already set on it
							//but new instances will get the property with the new value.
							$test->prototype->variable=4;
							
							//This instance has been created after changing the prototype so its "variable" will be 4;
							$foo=new test();
							
							echo $test->variable; //Prints: 3
							echo $foo->variable; //Prints: 4
						

Changelog

1.0

  • First release