Re: [RFC] Scalar Type Hints

From: Date: Thu, 01 Jan 2015 15:28:40 +0000
Subject: Re: [RFC] Scalar Type Hints
References: 1 2 3  Groups: php.internals 
Request: Send a blank email to internals+get-80049@lists.php.net to get a copy of this message
Hi Maxime, > On 1 Jan 2015, at 13:29, Maxime Veber <nek.dev@gmail.com> wrote: > > I was expected an RFC like this in PHP for a while. I'm happy somebody made one, thanks. Glad to hear that. > But something hit me in that. even if you can't give an objet, you can give any scalar > type that will be cast. > I'm not sure this behavior is very relevant. > > Actually if I ask for a string, why the user could be specify an int without getting error ? > > Consider the following PHP 5.6 code: > > function foo($a) { > if (!is_string($a)) { > throw new \Exception('You need to give a string'); > } > } > > Using your type hinting does not fix the problem of string checking because the value will just > be cast if it's an integer. Ofc if the user give an object it's ok. > But why not throw a message error in any cases ? For various reasons, PHP has always been a weakly-typed language, so we allow conversions between scalar types when they make sense. An integer isn’t a string, sure, but it can be simply converted to one and the result makes sense, so I think that’s why we allow it. It would still error in some cases, like an object without __toString for a string parameter, or an array for an integer parameter. Thanks. -- Andrea Faulds http://ajf.me/

« previous php.internals (#80049) next »