On Tue, Aug 14, 2012 at 12:46 AM, Stan Vass <sv_for...@fmethod.com> wrote:

> I've felt the need for this for some time.
>
> Proposed syntax:
> -------------------------
>
> $x = (InterfaceName) $container->service;
>
> Proposed behavior:
> ---------------------------
>
> Checks if the instance if an instance of the given class/interfaces. If
> yes, does nothing, if not, issues a fatal error. Pseudo code:
>
> $temp = $container->service;
> if ($temp instanceof InterfaceName) {
>     $x = $temp;
> } else {
>     trigger_error('The object can not be cast to InterfaceName');
> }
>
> Use cases:
> ----------------
>
> As my example hints, the intent is to provide type safety and hinting for
> the increasingly used dependency injection container pattern.
>
> It's useful to provide type safety also for all similar patterns which may
> not return a result of the expected type: Registry, ServiceLocator, Factory
> etc.
>
> Additionally to runtime type safety, this will also serve to editors/IDEs
> as an inline hint to provide proper autocompletion, i.e. instead of this:
>
> /** @var $foo InterfaceName */
> $foo = $container->service;
>
> People can now just write:
>
> $foo = (InterfaceName) $container->service;
>
> Alternative syntax:
> --------------------------
>
> I realize "casting" isn't a perfect match as the behavior is equivalent to
> inline type hinting. On the other hand, casting and inline type hinting in
> dynamic languages often behave identically (see the casting behavior in
> ActionScript which combines type hints with a JS-like dynamic type system).
>
> And this syntax doesn't introduce new keywords. Still, alternative ways to
> implement this could be:
>
> 1. $foo = $container->service as InterfaceName;
> 2. $foo = $container->service is InterfaceName;
> 3. $foo = (InterfaceName $container->service);
> 4. InterfaceName $foo = $container->service;
>
> All of those would be fine, especially 4, which has precedent in other
> languages, and in PHP as well with typehinting and in catch blocks:  catch
> (ClassName $e) { ... }
>
> I'm ok with suggestions for any syntax that is as short, if it fits the
> behavior better.
>
> Feedback?
>
> Stan


I actually like the (InterfaceName) casting approach.  I can see how type
casting as an object instance could lead to all sorts of innovative coding
architectures.  I'm less enthused about the 4 alternatives you mentioned,
though.  But overall I think it's a pretty awesome idea.

--Kris

Reply via email to