12

Why does PHP only support type hinting for arrays and objects? I want to use a type hint like the following:

 protected function addServiceToken(string $token)
 {
    if(!array_key_exists($token, $this->service_tokens)) 
        $this->service_tokens[$token] = 'waiting'; 
    return $this->checkServiceTokenStatus($token);
 }

Instead of adding a less elegent call to is_string($token) to ensure that the proper type of argument is passed.

@Daniel Egeberg writes in an answer to a related question:

There is currently an implementation supporting this in the SVN trunk version of PHP, but it's undecided if that implementation will be the one that gets released in future versions of PHP, or if it will be supported at all.

So, apparently someone (or somemany) besides myself would like to use this syntax and vice-versa. If the code has already been written why would anyone not want it included, particularly as type-hinting is an optional choice? I personally would like to see PHP continue to adopt more features like this which encourage "good" coding practices like checking the type of a variable before using it. What benefit did they see in excluding scalar types when they added type hinting to the language?

4
  • 11
    Probably the same reason they are undecided about declaring return type, which would really promote good coding style, but then they will probably change the name of the language to Java Commented Nov 29, 2011 at 21:59
  • The benefit of not making automatic type casting (based on operator) useless. Commented May 20, 2013 at 17:03
  • 1
    See the article Scalar type hinting is harder than you think. Commented May 9, 2014 at 20:08
  • @JoeCoder I appreciate this most valuable insight. I seek to go beyond simple syntax and understand. I do not understand why these type of questions are closed when to me they are often the most useful in improving stylistically. Commented May 28, 2014 at 20:04

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.