2013/9/24 David Soria Parra <d...@php.net>

> Lazare Inepologlou <linep...@gmail.com> schrieb:
> > I use anonymous classes very frequently in Java and in C#, and I would
> say
> > that they are quite useful. However the examples given in the RFC are
> > really bad ones. Why on earth would you need a constructor for an
> anonymous
> > class? Anonymous classes are used to implement quickly some interface.
> > Frankly, constructors are not part of any interface. Besides a
> constructor
> > is totally useless in an anonymous class as it will never be called after
> > the object is created.
>
> The need for anonymous classes in Java mostly comes from implementing
> interfaces on demand due to the lack of lamdas and the requirements of
> a strongly typed language. PHP has lambdas and it doesn't require you
> to match typing. Therefore I think the preferred way for most of the
> use cases is to use a lambda or if a bigger implementation is necessary,
> to give it a name. Due to namespacing you don't pollute the global scope
> anyway. Therefore I don't see much reason left as to why add anonymous
> classes and I really have a hard time finding a use case, except for trying
> to write PHP as you would write Java (which most likely is a bad idea).
>
>
There are many use cases where anonymous classes are useful, even in the
presence of lambdas. I use them quite often when dealing with graphical
interfaces and templates. Here is an example:

abstract class MyFancyHtmlListView extends UI {
  protected function IsHeaderVisible(){ return true; }
  protected function GetListItemMenu(){ return null; }
  protected function OnItemClick( $item ){ }
  protected abstract function RenderListItem( $item );
  public function Render(){
    // echo ...
  }
}

With anonymous classes we could do something like this:

<?= new MyFancyHtmlListView(){
  protected function IsHeaderVisible(){
    return false;
  }
  protected function RenderListItem( $item ){
    // echo ...
  }
} ?>

The biggest advantage is that a missing RenderListItem could be statically
verified.

It is just a pattern that follows a different way of thinking: Instead of
having a list of parameters (including lambdas), we have standard methods
that take advantage of all the nice properties of OOP such as abstraction,
inheritance and polymorphism.




Lazare INEPOLOGLOU
Ingénieur Logiciel

Reply via email to