Hey Robert,

> On 12 Feb 2015, at 16:15, Robert Stoll <p...@tutteli.ch> wrote:
> 
> There are several programming languages which do support dynamic typing and 
> method overloading somehow (Clojure, Erlang, Prolog, Cecil and certainly 
> more).  Most of them use a multi-method approach and I think if PHP would 
> introduce function/method overloading, then such an approach would be 
> appropriate.

Interesting, I should maybe look into those. I’m not sure if all of those are 
really… “dynamic” as such. Are you sure the overloading you’re referring to 
there isn’t pattern-matching?

> Right now, I need to implement the dynamic dispatching quasi myself which 
> might be more verbose but is also more cumbersome (and uglier IMO). Consider 
> the following (fictional example):
> 
> I want to write a Logger-Service which provides one public method "log" which 
> writes all kind of objects to a log. The corresponding classes do not all 
> belong to my code base, are part of third party libraries respectively, so I 
> am not able to introduce some interface which all classes implement. The 
> strategy pattern is certainly a good idea for this problem but nevertheless, 
> somewhere I need to have the distinction based on many if/else with 
> instanceof (latest in the LoggerStrategyFactory) -- off topic, if someone has 
> a better design approach to handle this problem, then let me know it in a 
> private message, would be interesting as well ;)
> 
> class Logger{
>  public function log($x){
>    if($x instanceof Foo){
>       logFoo($x);
>    }else if($x instanceof Bar){
>      logBar($x);
>    }
>    //...
>    }else{
>       throw new Exception("type ".gettype($x)." not supported");
>    }
>  }
>  private function logFoo(Foo $f){
>    //..
>  }
>  private function logBar(Bar $b){
>   //..
>  }
>  //...
> }
> 
> With method overloading I could write the following, removing the hassle to 
> write the dynamic dispatch myself:
> 
> class Logger{
>  public log(){
>    $this->_log($x);
>  }
>  private function _log(Foo $f){
>    //..
>  }
>  private function _log(Bar $b){
>   //..
>  }
>  //...
>  private function _log($x){
>    throw new Exception("type ".gettype($x)." not supported");
>  }
> }
> 
> Which is cleaner IMO.

We could also add some sort of pattern-matching syntax which could do the same 
thing, but would have usefulness beyond merely dispatching to multiple methods.

--
Andrea Faulds
http://ajf.me/





--
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: http://www.php.net/unsub.php

Reply via email to