Hello Internals.

I'm a userland PHP developer, I readed all the proposals about type
hinting and did some code writing with type hinting to see how it
looks like. Well, to my understanding it's a mess if both types of
type hinting are done.

Here is an example of a function:
function calculate_age($birthday_date, $year) {}.

How to type hint it?
Strictly or softly? Really depends on the case. If you use it
somewhere deep inside your API, than it probably should be strict. But
if not? You could get your params from anythere: database (as
strings), POST or GET (again strings), $year can be simply date('Y')
as a string or just some value from config as int. So what we see is
that strict type hinting is just too much here. Weak type hinting is
more appropriate. But do we need it at all? If I get my data from POST
or GET i'll certanly do a validation on them - trim the $year and
check it for is_numeric, $birthday_date will be checked by preg_match
to de a valid date format and then will be checked by checkdate() if
it's valid date. That leaves even weak type hinting without any real
work. If I get it from database, I'll just pass it to function,
because that data is validated and contains proper values - in this
case strict type hints will give an error for $year, because it's a
string from database and soft will just make a conversion to int so it
would happen earlier that calculations.

Strict type hint's are useless in works with database results. And
mostly in WEB we work with database results and data from GET/POST or
other sources like XML, JSON API's and so on. There data is always as
strings. Do you want that data be converted to appropriate types by
userland code something like this?
$res = $mysqli->query($sql);
if ($res && $res->num_rows) {
    while ($row = $res->fetch_assoc()) {
        foreach ($row as $k => $v) {
            if (is_numeric($v)) {
                $row[$k] = (int)$v;
            }
        }
    }
}
// Now we can use strict type hints!

Looks like it's the weak type hinting that will be used in most cases.

The question I have what will be in such case with weak type hints?:
function test(array $data) {}
test(1);

For me that should be an error, but the PHP mechanics of type
conversions should convert that 1 to array(1). Same with objects. In
object or array case most people probably will want a big error so
they could investigate there is a bug and fix it. But with strings and
integers/floats I'd prefer just silent type conversion. But you people
like consistency and I'd predict you would do int to array conversion
with weak type hinting, same as string to int/float.

A little bit messy, but I believe you got the point. My IMHO is that
a). There can't be a consistent way for all type conversions b).
Strict type hinting is out of the question.

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

Reply via email to