Last active
December 21, 2015 20:49
-
-
Save ichiriac/6364394 to your computer and use it in GitHub Desktop.
An experiment to implement the Javascript Prototype principle in PHP 5.3
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class jPrototype { | |
protected static $prototype = array(); | |
public static function prototype() { | |
if ( !self::$prototype ) { | |
self::$prototype = new self(); | |
} | |
return self::$prototype; | |
} | |
public function __set($property, $value) { | |
$this->$property = $value; | |
} | |
public function __get($property) { | |
if ( $property === 'prototype') { | |
return self::prototype(); | |
} | |
if ( isset($this->$property) ) { | |
return $this->$property; | |
} else { | |
return isset( self::$prototype->$property ) ? | |
self::$prototype->$property : null; | |
} | |
} | |
public function __call($func, $args) { | |
if ( !($fn = $this->__get($func)) ) { | |
throw new BadMethodCallException( | |
'Undefined function ' . get_class($this) . '::' . $func | |
); | |
} | |
return call_user_func_array( | |
$fn, | |
$args | |
); | |
} | |
} | |
/** | |
* The initial class | |
*/ | |
class Foo extends jPrototype { | |
} | |
Foo::prototype()->hello = function() { | |
return 'Hello Foo Initial'. "\n"; | |
}; | |
// using the prototype declaration | |
$obj = new Foo(); | |
echo $obj->hello(); | |
// update the declaration | |
Foo::prototype()->hello = function() { | |
return 'Hello Foo Updated'. "\n"; | |
}; | |
echo $obj->hello(); | |
// creating a new class | |
$bar = new Foo(); | |
$bar->hello = function() { | |
return 'Hello from bar (only)' ."\n"; | |
}; | |
echo $bar->hello(); | |
// test that not changed the foo prototype | |
echo $obj->hello(); | |
// updating the prototype from an instance | |
$bar->prototype->hello = function() { | |
return 'I was globally changed from $bar !'."\n"; | |
}; | |
echo $obj->hello(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment