Created
December 4, 2015 09:09
-
-
Save nexpr/befa2ba8869cd702d91f to your computer and use it in GitHub Desktop.
prototype chain in php
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 Object{ | |
function __call($name, $arguments){ | |
if(is_object($this->__proto__)){ | |
$meth = $this->__proto__->$name; | |
array_unshift($arguments, $this); | |
return call_user_func_array($meth, $arguments); | |
}else{ | |
throw new Exception(); | |
} | |
} | |
function __get($name){ | |
if(is_object($this->__proto__)){ | |
return $this->__proto__->$name; | |
}else{ | |
return null; | |
} | |
} | |
function __construct($arr = null){ | |
if(isset(self::$prototype)){ | |
$this->__proto__ = self::$prototype; | |
}else{ | |
$this->__proto__ = null; | |
} | |
if(is_array($arr)){ | |
foreach($arr as $key => $val){ | |
$this->$key = $val; | |
} | |
} | |
} | |
static $prototype = null; | |
} | |
Object::$prototype = new Object(); | |
Object::$prototype->toString = function($This){ | |
return json_encode($This); | |
}; | |
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
// usage sample | |
class Sample extends Object{ | |
function __construct($data){ | |
$this->__proto__ = Sample::$prototype; | |
$this->data = $data; | |
} | |
static $prototype = null; | |
} | |
Sample::$prototype = new Object(); | |
Sample::$prototype->a = 200; | |
Sample::$prototype->double = function($This){ | |
return $This->data * $This->data; | |
}; | |
Sample::$prototype->plus = function($This, $num){ | |
return $This->data + $num; | |
}; | |
$s = new Sample(10); | |
var_dump( $s->a ); | |
var_dump( $s->double() ); | |
var_dump( $s->plus(1) ); | |
$a = new Object(["a" => 1]); | |
$b = new Object(["b" => 2]); | |
$c = new Object(["c" => 3]); | |
$a->__proto__ = $b; | |
$b->__proto__ = $c; | |
var_dump($a); | |
var_dump($a->a); | |
var_dump($a->b); | |
var_dump($a->c); | |
var_dump($a->toString()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment