Is it possible to write strictly typed PHP code?

后端 未结 9 894
陌清茗
陌清茗 2020-12-14 15:34

For example, is it possible to write code like this:

int $x = 6;
str $y = \"hello world\";
bool $z = false;
MyObject $foo = new MyObject();

9条回答
  •  醉话见心
    2020-12-14 15:52

    Something you might try in order to simulate a poor man's strict type checking is using assert() to force the output to be of a particular type before you return it:

    /**
     * Get Balance
     *
     * @return int
     */
    function getBalance()
    {
        /* blah blah blah */
       $out = 555; //Or any numeric value
       assert('is_int($out)');
       return $out;
    }
    

    So you keep your assertions active all throughout development and testing, sort of like the checks the compiler does at compile-time.

    Granted, the assert() page is keen to assert that you shouldn't use assertions to check input parameters, but rather use normal conditionals to check them.

    This answer had what I thought was a good rule:

    The rule of thumb which is applicable across most languages (all that I vaguely know) is that an assert is used to assert that a condition is always true whereas an if is appropriate if it is conceivable that it will sometimes fail.

    If you're simulating strict type-checking (writing your code to viciously maintain types; not trying to validate input from the outside), then you ought to be certain what the type is unless you've made a mistake.

    Update:

    There's also this: http://hacklang.org/ Facebook's PHP-based language with static typing.

提交回复
热议问题