note 75219 deleted from language.oop5.typehinting by felipe

From: Date: Mon, 24 Mar 2008 23:22:34 +0000
Subject: note 75219 deleted from language.oop5.typehinting by felipe
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-137530@lists.php.net to get a copy of this message
Note Submitter: Andrea Giammarchi ---- Type Hinting is a good idea but PHP 5 doesn't support explicit overload so this is my Type Hinting overload proposal using "magic" __call method and a bit of Reflection. <?php // just two classes ... class A{ private $value; function __construct($value){ $this->value = $value; } function __toString(){ return ''.$this->value; } } class B extends A{} // just another class with my fake Type Hint overload class Overload { protected function doSomething0(A $a) { return 'Recieved an A instance with value: '.$a; } protected function doSomething1(B $b) { return 'Recieved a B instance with value: '.$b; } protected function doSomething2(A $a, B $b) { return $this->doSomething0($a).' and '.$this->doSomething1($b).' too'; } protected function doSomething3(B $b, A $a) { return $this->doSomething1($b).' and '.$this->doSomething0($a).' too'; } // magic __call public function __call($method, $arguments){ for( $methods = call_user_func(array(new ReflectionObject($this), 'getMethods')), $re = '/^'.$method.'[0-9]+/', $i = 0, $j = count($methods), $k = count($arguments); $i < $j; $i++ ) { if( preg_match($re, $methods[$i]->name) && $methods[$i]->getNumberOfRequiredParameters() === $k ) { $params = $methods[$i]->getParameters(); for( $l = 0, $call = true; $l < $k && $call; $l++ ) $call = call_user_func(array(new ReflectionObject($arguments[$l]), 'getName')) === $params[$l]->getClass()->name; if($call) return call_user_func_array(array($this, $methods[$i]->name), $arguments); } } } } // just a test to check my proposal $o = new Overload(); $a = new A('test one'); $b = new B('test two'); echo $o->doSomething($a), '<br />', $o->doSomething($b), '<br />', $o->doSomething($a, $b), '<br />', $o->doSomething($b, $a), '<br />'; ?> That's all, do You like it?

« previous php.notes (#137530) next »