Is it possible to write strictly typed PHP code?

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

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

And is it possible to define functions like this:

public int function getBalance()
{
   return 555; //Or any numeric value
}

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 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."

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


In PHP 7 are implemented "Scalar Type Declarations", eg:

public function getBalance(): int {
    return 555;
}

You need to declare, that you will use strict types:

<?php
    declare(strict_types=1);

    function sum(int $a, int $b): int {
        return $a + $b;
    }

    sum(1, 2);
?>

More information: https://wiki.php.net/rfc/scalar_type_hints_v5


PHP is not strictly typed, so no. That said, it does support limited type hinting on functions - that's as close as it gets.

链接地址: http://www.djcxy.com/p/57624.html

上一篇: 计算PHP / MySQL中的排名

下一篇: 是否可以写严格类型的PHP代码?