note 75219 added to language.oop5.typehinting

From: Date: Fri, 18 May 2007 14:08:11 +0000
Subject: note 75219 added to language.oop5.typehinting
Groups: php.notes 
Request: Send a blank email to php-notes+get-126687@lists.php.net to get a copy of this message
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? ---- Server IP: 213.92.11.19 Probable Submitter: 84.220.44.148 ---- Manual Page -- http://www.php.net/manual/en/language.oop5.typehinting.php Edit -- https://master.php.net/note/edit/75219 Del: integrated -- https://master.php.net/note/delete/75219/integrated Del: useless -- https://master.php.net/note/delete/75219/useless Del: bad code -- https://master.php.net/note/delete/75219/bad+code Del: spam -- https://master.php.net/note/delete/75219/spam Del: non-english -- https://master.php.net/note/delete/75219/non-english Del: in docs -- https://master.php.net/note/delete/75219/in+docs Del: other reasons-- https://master.php.net/note/delete/75219 Reject -- https://master.php.net/note/reject/75219 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#126687) next »