Scalar type hints and strict typing in PHP 7

catgirl

Administrator
Staff member
Administrator
May 28, 2020
155
28
22
United States
envyforums.net
A new feature in PHP 7 is scalar type hints and the addition of optional strict typing. Before reading this post you may find it helpful to read my previous post on anonymous classes to better understand this post's code example.

You can use scalar type hints in function parameter declarations:
PHP:
<?php
  function printText(string $text) {
      return $text;
  }
?>
As well outside the parameters to hint at the return type:
PHP:
<?php
  function printText(string $text) : string {
      return $text;
  }
?>
And optionally enable a strict types mode where the code will throw an error if you attempt to run it in a situation where the return types or argument types do not match the provided scalar type hints.
PHP:
<?php
  declare(strict_types=1);
  function printText(string $text) : string {
      return $text;
  }
?>
I've adapted my previous example on anonymous classes to utilize scalar type hints and strict typing.

PHP:
<?php
    declare(strict_types=1);

    $name = "Catgirl";
    $age = 21;

    $person = new class($name, $age) {
        private $name;
        private $age;
        
        public function __construct(string $name, int $age) {
            $this->name = $name;
            $this->age = $age;
        }

        public function getName() : string {
          return $this->name;
        }

        public function getAge() : int {
          return $this->age;
        }
    };
?>
This optional feature allows you to use PHP like a strict typed language while leaving the choice to the developer rather than forcing one way or another on the developer. What do you think about this PHP feature? Will you use scalar type hints? What about strict typing mode?