On 09/25/2013 02:02 PM, Terence Copestake wrote:
1) Anonymous classes in PHP would support a constructor, so I don't see
the need for use to be utilized here, it would just clutter declarations
and the patch.


This works, but it's more effort for the programmer and arguably just
moving the "clutter" from the declaration to the constructor.

e.g.

(new class ...
     protected $value;
     public function __construct($value)
     {
         $this->value = $value;
     }

     public function doSomething()
     {
         echo $this->value;
     })($val)

vs.

(new class ...
     public function doSomething() use ($val)
     {
         echo $val;
     })

It gets even uglier for passing by reference.


2) Again, constructors can be used, and is less confusing than introducing
a new variable, but I'm open to persuasion if the idea is liked in general
...


This is fine when working with only a handful of values, but what about
needing access to a large number of values? What about making (especially
protected) method calls within the anon class?

Along the same vein, why did we even bother having "use" and $this for
closures, if you can after all just pass everything as arguments?

If there are realistic and elegant alternative solutions to the problems
presented, that's fair enough. Rejecting something because it's not as
simple to implement and you can hack around it in user code anyway...
that's a dangerous way to go about your business.


The first example doesn't make good sense:

> (new class ...
>      protected $value;
>      public function __construct($value)
>      {
>          $this->value = $value;
>      }
>
>      public function doSomething()
>      {
>          echo $this->value;
>      })($val)

If $value is protected then how are you passing it in from outside as $val ?

If your anonymous class needs access to protected methods (which in turn might want to read private members) then there's already an established way of declaring that:

<?php
class Outer {
    private $dice;

    public function __construct($dice) {
        $this->dice = $dice;
    }

    protected function protectedMethod() {
        return $this->dice;
    }

    public function publicMethod() {
        return new class extends Outer {
            public function forwardToProtectedMethod() {
                $this->protectedMethod();
            }
        }($this);
    }
}
var_dump((new Outer($_SERVER))->publicMethod());
?>

This works now, as you expect it too ... not elegant enough ?? you don't think use() everywhere might be a little bit much ??

Lets try to keep it as simple as possible, I think ...

Cheers

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

Reply via email to