May 22, 2016 by Christoff Truter PHP
Almost a decade ago I wrote a post about strongly typed PHP, in which I proposed a very crude workaround, essentially faking strong typing using magic methods. The post was met with a lot of mixed reactions, but received quite a lot of visitors over the years (definitely some interest in the subject).
PHP won't ever (dare I say) become a strongly typed language, but I do believe that in the near future it will become a gradually typed language (like TypeScript).
Which basically means we can statically declare all member types if we want to, but we're not forced to (type declaration is optional).
Now recently (with the great coming of PHP 7.x), developers introduced scalar type declaration, thereby making it possible to type hint (declare) the four scalar types (bool, int, float, string) on function arguments as well (type hints used to be limited to objects, arrays and callables), additionally return type declarations were also introduced.
class Person { private $age; public function __construct(int $age) { $this->age = $age; } public function getAge() : int { return $this->age; } }
$a = new Person(33); $b = new Person(33.4); $c = new Person(33.6);
$d = new Person("33");
$e = new Person("33a"); Warning displayed - A non well formed numeric value encountered
$f = new Person("a"); throws TypeError - must be of the type integer
declare(strict_types=1);
class Person { public int $Age; // Not possible yet }
Like you might have noticed, I finally got around to playing around with the latest version of PHP (7.0.6 at the time of writing this post). I am planning to do did a little write-up of some of the new features just to get everybody (and myself for that matter) up to speed.