Re: [RFC] Scalar Type Hinting With Casts (re-opening)

From: Date: Sun, 13 Jul 2014 15:51:19 +0000
Subject: Re: [RFC] Scalar Type Hinting With Casts (re-opening)
References: 1 2 3 4 5 6 7 8 9  Groups: php.internals 
Request: Send a blank email to internals+get-75422@lists.php.net to get a copy of this message
On 13/07/2014 16:35, Jocelyn Fournier wrote:
That seems both inconsistent and less useful than a hybrid juggling + validation approach.
Than means you find currently inconsistant than $foo = (int) 'abc'; works but not $bar = (object) 'abc'; ? :)
Well, the ability to cast to an object at all is pretty wacky, since PHP has no standard base class for objects, nor any mechanism to cast to or from specific classes, etc. Perhaps this example is more appropriate: function wants_array(array $foo) { var_dump($foo); } wants_array('abc'); // Error wants_array( (array)'abc' ); // OK - parameter passed is array(0 => 'abc') As you can see, it's perfectly possible for the value to be cast, but the "type hint" does not do so, it rejects the value. Previous proposals (e.g. [1]) have suggested a distinct syntax for the "automatic cast" which you seem to be favouring, which would allow us to write this, avoiding the inconsistency: function casts_to_array((array) $foo) { var_dump($foo); } casts_to_array('abc'); // OK - parameter interpreted as (array)'abc' and thus array(0 => 'abc') This is just sugar for: function casts_to_array($foo) { $foo = (array)$foo; var_dump($foo); } As such, it neither requires, nor is required for, additional warnings around lossy casts. [1]: http://blog.ircmaxell.com/2012/03/parameter-type-casting-in-php.html -- Rowan Collins [IMSoP]

Thread (250 messages)

« previous php.internals (#75422) next »