On Thu, Dec 9, 2010 at 1:09 AM, Stefan Marr <p...@stefan-marr.de> wrote:

> Hi Nathan:
>
> On 09 Dec 2010, at 08:44, Nathan Nobbe wrote:
>
> > Hi,
> >
> > I think traits will lend themselves to frequent runtime checking against
> the
> > type of class in which they were used.  Consider a trait designed for use
> > with an Iterator class; the first thing might be to check the type of
> $this.
> Why would you need such a check?
>

To avoid a fatal error at runtime.


> You want to ensure that the class that is using your trait obeys a certain
> interface, right?
>

Not really, it's so the trait can guarantee the class it has been used with
implements a given interface that it may need to accomplish its job.


> More specifically, you need it to implement a number of methods of an
> interface, correct?
> So, why not asking for it explicitly?
>
> <?php
> trait InnerIteratorImpl {
>  abstract function next();
>
>  public function apply() {
>     do somthing with $this->next() ...
>  }
> }
> ?>
>
> Does that what you want it to do?
>

Not really, in this example above the trait is self-contained, implementing
all the methods of a particular interface so it's reasonable to expect from
one of the methods in the trait, another of the Iterator interface to be
there.

What I'm getting at is the scenario when a trait is designed to be used in
concert with the class in which it is being used.  In this case the trait
expects certain functions to be available on the class in which it is used
with.  If the methods aren't there (or checked for at runtime) a fatal error
is raised.

A quick example
<?php
class A {
  use AHelper;

  function blah() {}
}

trait AHelper {
  function meh() {
    // hoping we get used w/ instances of A ...
    return $this->blah() * 5;
  }
}

class B {
  use AHelper;

  /// waiting for a runtime error if blah() is ever called ..
}
?>

Do you see what I mean?

-nathan

Reply via email to