RE: [PHP-DEV] RE: Optional scalar type hinting

From: Date: Fri, 04 Jan 2008 00:29:19 +0000
Subject: RE: [PHP-DEV] RE: Optional scalar type hinting
References: 1  Groups: php.internals 
Request: Send a blank email to internals+get-34378@lists.php.net to get a copy of this message
You have a point, but for input in general non type-hinted functions should be used. Your first example shows a scenario in which not to use type hinting, because all $_REQUEST input is in string form. However when dealing with internal functions and methods, type hinting can prevent flawed interaction between multiple developer's code, as well as enforce a consistent API. On Thu, 2008-01-03 at 22:13 +0000, Amir Abiri wrote: > The question that pops to my mind by reading this thread is "what's wrong with the > following code": > > function add(int $a, int $b) > { > return $a + $b; > } > > add($_REQUEST['a'], $_REQUEST['b']); // Assume $_REQUEST['a'] == > '1' and $_REQUEST['b'] == '2'. > > And the truth is that if I was forced to explicitly cast I would be annoyed. I can't say I > see that > cast as promoting better code or more readable code - It would just clutter the code and be > annoying. PHP does a lot of type juggling for me, why annoy me all of a sudden? > > As for the argument of "it's optional" the problem with it is that most code > that the average PHP > developer writes is constrained PHP that other PHP developers have already written, either > library > or code base. The feature may be optional for the developer writing the function or method, but > it > is enforced on the developer who's using it. This is exactly where the "direction of > the platform" > arguments come into play. > > So I'm thinking, "No". > > But then I was thought about it further and thought about this scenario: > > $a = some_functions(); // Let's say it returned NULL. > $b = $_REQUEST['b']; // Let's say this is ''. > > add($a, $b); > > > Very bad. Hell I'd like to have some easy way of telling off the developer who tries to do > that to > my function. Enter type hints. > > > Here are a few more examples: > > concatenate(string $str1, string $str2) > { > return $str1 . $str2; > } > > concatenate('x', 1); // Great, what's the big deal ? > concatenate(NULL, false); // Hmm... > concatenate($obj1, $obj2); // $obj1 and $obj2 have __toString(). > > > So the bottom line is that it seems to me that what would be really useful is not strict type > hinting, but more like "Juggling hinting". i.e differentiate between an > "OK" type juggle and a "bad" > type juggle. Silently perform the first, while emit a small notice or warning for the later. > > Just my... erm, 2$... :-) > > A >

« previous php.internals (#34378) next »