2009/7/10 Alain Williams <a...@phcomp.co.uk>

> On Fri, Jul 10, 2009 at 01:35:45PM +0300, Ionut G. Stan wrote:
> > On 7/10/2009 13:23, Giovanni Giacobbi wrote:
> > >On Fri, Jul 10, 2009 at 02:44:52AM +0200, troels knak-nielsen wrote:
> > >[...]
> > >
> > >>For example, instead of:
> > >>
> > >>     function addFive(int $x) {
> > >>       return $x + 5;
> > >>     }
> > >>
> > >>You would simply do:
> > >>
> > >>     function addFive(is_numeric $x) {
> > >>       return $x + 5;
> > >>     }
> > >>
> > >>Since $x is guaranteed to be numeric, it is safe to to arithmetic on
> > >>it. No reason to explicitly type cast here.
> > >>
> > >>
> > I like it too. Not only it solves the initial problem, but it also
> > allows userland extensions. For example,
> > the current patch does not provide checks for callables, but we already
> > have is_callable in the core.
>
> Hmmm, but it makes simple cases more complicated and slower. But I do like
> the
> idea of generalising it with a function to handle 'strange' cases.
>
> So, we have 3 syntaxes:
>
> 1)      function Foo(int $x) {
>
>  $x is tested to be integer, if it isn't an error is raised - either by
> exception
>  or just a fatal error.
>
>  A problem with this is that it could yeild some surprising results, eg:
>
>        Foo(4/2);               -- OK
>        Foo(4/3);               -- FAIL since 4/3 yeilds a float
>
>  In this last case people would learn to:
>
>        Foo((int)(4/3));
>
>
> 2)      function Foo((int) $x) {
>
>  $x is cast to int, ie converted iff possible - otherwise an error is
> raised:
>        int -> int -- OK
>        float -> int -- OK if in the range for integer
>        string -> int -- OK iff it is 100% clean:
>                '10' - OK
>                '10.1' - OK as string -> float -> int
>                '10ten' - FAIL/ERROR
>        etc
>
>   What happens when someone tries to use this syntax where he is casting to
> an object ?
>   I suggest that this fails unless the object has a __cast method, in which
> case that is invoked:
>
>        function Foo((MyObject) $x) {
>                ...
>        }
>
>        class MyObject {
>                function __cast($x) {
>                        if( ..... )
>                                return new Foo('abcd', $x);
>                        ....
>                }
>                ...
>        }
>
>
> 3)      function Foo(is_int($x)) {
>
>  Function is_int is called, an error is raised if it returns false.
>

But then you're complicating it to the point where it's no longer much more
useful than just calling the is_numeric method in the function body. Plus
there's no longer the advantage of optimisers knowing the data-type.

Lewis.

Reply via email to