PHP type hinting - hard or soft?

    Good afternoon,% username%!

    Today I would like to discuss the topic of type hinting in PHP. At the moment, there is a heated discussion on the development mailing list on this topic and discusses which approach should be used and how it will work. Your humble servant is also actively involved in this discussion.

    You can start reading the discussion here and move on by clicking on next in thread.



    Two main implementation options are discussed - strict typing and soft.
    • Strong typing is checking the type of a variable when passing a parameter to a function. Any mismatch results in an error or notice
    • Soft typing is a check both by type (prohibition of passing array instead of integer), and the ability to automatically convert certain types (more on this later).


    Personally, I support the second option. And that's why.

    Firstly, this option supports automatic translations of the form integer => float, float => string, string -> float, string => integer. You say, what about “123abc” => int => 123 !? In this case there will be an error. And this is necessary so that we would not have to deal with manual type conversion every time we select something from the database. You must agree that each time you explicitly convert the record ID to int, it means writing a lot of additional code (whoever doesn’t know, most libraries for working with databases in PHP give all the data as strings, regardless of the type of column in database). And it is precisely to the person who sings that I am against strict typing — it will bring more problems than good.

    In general, the mechanism of work is supposed to be:
    • "11" turns into integer and float
    • 11 turns into string and float
    • 11.1 turns into string, float is an error.
    • "11.1" turns into a float, integer - error
    • "11acd" - an error for both integer and float
    • For a bool hint, all values ​​are converted to true / false according to traditional PHP rules
    • Converting from simple types (bool, int, float, string) to array or object and vice versa always gives an error.
    • Type hinting of arrays and objects remains as it is now


    In general, if you have something to say, subscribe to the php-internals mailing list and write to it. If you are too lazy to do this - I can send a message for you.

    What do you think about this,% username%? What approach do you vote for?

    UPD1: I will summarize the discussion in a general topic and send it to the internals mailing list. So you have the opportunity to express an opinion as a Russian PHP comunity.

    Also popular now: