Hi Nathan, On Thu, Apr 30, 2015 at 6:41 AM, Nathan Bruer <nathanbr...@gmail.com> wrote:
> This has been a big issue that I have ran into many times in the past for > large framework projects, instead of building it out with "strict" types > like: int, float, string, exc... It makes more sense to allow a user to > define a psudo-type themselves which PHP will pass the arguments into to be > "cleaned" by the user then let the function deal with the arguments. > > For example: > function force_int($value){ > return (int) $value; > } > function must_be_string($v){ > if(!is_string($v)){ > throw new Exception("Not String"); > } > return (string) $v; > } > > function foo(*force_int $val, *must_be_string $str){ > // $val will always be an int if it ever gets here > // $str will always be a string if it gets here > echo $val, " ", $str; > } > foo("foo", "bar"); // returns '0 bar' > foo("1", "2"); // returns '1 2' > foo(1, 2); // fatal error because second argument threw exception > foo(1, "2") // returns '1 2' > foo("hi", 2) // fatal error because second argument threw exception > foo("hi", "2") // returns '0 2'; > I agree. Forcing type is headache and such check is useful. The problem with this approach is overhead. I would like to resolve this in 2 ways. 1. DbC - Check parameter types during development by DbC and make sure all callee satisfies contract. 2. True weak type hint - Make weak mode type hint truly weak. Accept any form of the specified types. Since we won't have DbC for PHP 7.0, I'll discuss only option 2. function foo(int $i) { switch(gettype($i)) { case 'integer': case 'float": foo_numeric($i); break; default: // We don't want to accept gmp/string throw new Exception('Type error'); } } Ideal solution would be DbC. Anyway, above example is a little more efficient than calling pseudo type checker functions (for now). Pseudo type checker is useful and requires less code. I'm neutral to have it or not. Regards, -- Yasuo Ohgaki yohg...@ohgaki.net