Is it possible to write strictly typed PHP code?

后端 未结 9 769
陌清茗
陌清茗 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 16:10

    Edit: This answer applies to versions of PHP 5.6 and earlier. As noted in recent answers, PHP version 7.0 and later does have some support for this


    Original answer:

    No. There is only support for type hinting since php5, but "Type Hints can only be of the object and array (since PHP 5.1) type. Traditional type hinting with int and string isn't supported."

    In PHP 7 are implemented "Scalar Type Declarations" see the answer below.

    That is as far as php currently goes, and as far as it should go if you ask me.

    0 讨论(0)
  • 2020-12-14 16:15

    Unfortunately NO! I am at the end of a big project now that involves a lot alogorithms (graph theory, circuits etc) and I wish I hadn't choose php.

    I have been using php for about 10 years, and still believe it is a good language, however one have to decide! What is bad for me, lack of strict typing might be good for someone else.

    In addition, I want to mention, that I often wrote extra code for supporting strict typing, just a plain example is this:

    if (is_array($r) && count($r)===0)
    

    and the errors and hidden situations etc that were revealed are beyond explanation.

    There were mistakes and situations that I would never been able to think/detect apriori, writing all these extra code was not enjoying but at least it will save me from silly mistakes!

    If I would go back, maybe I would chose php for the web part, you know getting and showing data to the user, php is just great for that, handling string, arrays, talking to the database etc etc, but for the main core, algorithms etc I would go for C++, maybe haskell.. don't know, at least something strictly typed.

    0 讨论(0)
  • 2020-12-14 16:15

    Since the answer is basically "no", an alternative: A PHP "linter", which should catch some of the things a compile-time check would catch in a staticly-typed language like C. Not the same, but should prevent some sillyness

    "Is there a static code analyzer [like Lint] for PHP files" lists many of these.

    0 讨论(0)
提交回复
热议问题