On 4 February 2015 at 10:13, Dmitry Stogov <dmi...@zend.com> wrote:
> This won't fit into "loosely-typed" PHP, and will lead to writing -
> sin((float)$x).

Hi Dmitry,

I think what people miss is that the place where the conversion from
an unknown type to an int takes place, is also the place where you
would put the human readable reason for why a certain type is needed:

function placeOrder(int $amount){...}

// Throws an exception with the provided message
// if the value cannot be converted to an int.
function getInt($value, $exceptionMessage) : int {...}

function processOrderRequest() {
    $amount = getInt($_REQUEST['amount'], "Sorry, the order amount
must be a whole number.");

    //Yay, our IDE can tell that $amount is an int if the code reached here.
    placeOrder($amount);
}

It's this join point between layers of code that make explicit strict
scalar types be so useful. On one side of that join point we don't
know (and shouldn't care) what the details of the value are. On the
other side of the join point we know that it is an int and don't have
to consider any other types.

I would love to have strict type hints in PHP, and this may sound
contradictory, but they would almost never ever get triggered in my
code. The only time they would be triggered is when there is a mistake
and I have missed converting something to the expected type.

Having the scalar type defined on the parameter allows for code
analysis tools to find errors. This would make cases where I forget to
convert them properly be almost non-existant. With asserts inside the
function those errors would only be detectable at run time.

btw For your exact example `sin((float)$x).` this is actually a case
where another scalar type of 'number' which is satisfiable by either a
float or an int would be useful, but that's definitely a step too far
before we have any scalar type hints.

cheers
Dan

-- 
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: http://www.php.net/unsub.php

Reply via email to