Categories
PHP

Type Declaration

A loosely typed language doesn’t offer the best performance since its compiler has more work to do when trying to determine the data types of its variables. On the other hand, the strict type languages consume less memory and give better performance at runtime than loosely typed languages. Since version 7, PHP offers the possibility of strict type function arguments, return values, and class properties (PHP 7.4), known as “Type declarations”.

This tutorial covers the following topics:

Type declarations

As of PHP 7 Type hinting is being referred to as Type declaration. PHP allows the developer to be more specific about what functions are getting and returning. You can optionally specify the type of parameters that the function needs and the type of result the function will return. To specify a type declaration, the type name should be added before the parameter name. Let’s first see an example:

<?php
function printMe( int $var ) {
 echo $var;
}

$v = 200;
$y = 'hello world';

printMe( $v );
//Prints 200

printMe( $y );
//Prints fatal error

In the above example, we specified that the parameter $var being passed to the printMe() function must be an int (integer). If the passed parameter is of a different type then the PHP halts and displays the error message:

Fatal error: Uncaught TypeError: printMe(): Argument #1 ($var) must be of type int, string given...

Return type declarations

PHP (since version 7) also supports “Return type declarations”. Similar to “Type declarations”, return type declarations specify the type of the value that will be returned from a function. To specify a return type declaration, the type name (followed by a colon :) should be added after the function’s closing parenthesis. See the following example:

function modulus(int $a, int $b) : int {
 return $a % $b;
}

$m = modulus ( 52 , 12 ); // 4

Error Handling in Type Declaration

If the given value is of the incorrect type, then an error is generated: in PHP 5, this will be a recoverable fatal error, while PHP 7 will throw a TypeError exception.

In the following example we’ll pass the incorrect data type, string:

<?php
function printMe(int $var) {
echo $var;
}

$v = "some example text";
printMe( $v );

The above example prints the following error on screen:

Fatal error: Uncaught TypeError: Argument 1 passed to printMe() must be of the type integer, string given...

List of Valid Declaration Types

We can use the following data types for “type declarations” and “return type declarations”:

Type Declaration in a Class or Interface

The parameter must be an instanceof the given class or interface name. To demonstrate we create a class User:

<?php
class User {
 private $fname = null;
 private $lname = null;
 function __construct($f, $l){
  $this->fname = $f;
  $this->lname = $l;
 }
 public function getFirstName() {
  return $this->fname; 
 } 
 public function getLastName() {
  return $this->lname;
 }
}

Next, we create a function to combine the first and last names with the type declared parameter of User class:

function getFirstLastName (User $u) : string {
 return $u->getFirstName() .' '.
        $u->getLastName();
}

Now we’ll create a new instance of the User class and pass it to getFirstLastName function:

$user = new User('Brain','Bell');
echo getFirstLastName($user);
//Brain Bell

Self Type Declaration

The parameter must be an instanceof the same class as the one the method is defined on. This can only be used on class and instance methods.

<?php
 Class Person {
  public function doSomething (Self $cls){
   /* if $cls is the instance of other class
      fatal and type error will be occured
   */
  }
 }

 Class User extends Person{ }
 Class World { }

 $person = new Person;
 $user = new User;
 $world = new World;

 $person -> doSomething ($person);
 $person -> doSomething ($user);

 //Fatal Error
 $person -> doSomething ($world); 
/*Uncaught TypeError: Person::doSomething(): Argument #1 ($cls) must be of type Person, World given...*/

Array type declaration in function argument and return value

function findInArray(array $arr) : array {
 foreach ($arr as $k => $v) {
  if ($v == 'something') {
   $arr[$k] = 'replaced';
  }
 }
 return $arr;
}

Declare Callable Type

<?php
function cbExample(callable $cb) : callable {
 $a = $cb();
 return function ($b) use ($a) {return $a + $b;};
}

//Or
function cbExample(callable $cb) : callable {
 $a = $cb();
 return fn($b) => $a + $b;
}

Declare Boolean and Integer Type

function boolIntExample(int $val ) : bool {
 if ($val == 0)
  return false;
 return true;
}

Declare Float and String Type

function floatStringExm(float $val ) : string {
 return "Total: $val";
}

Declare Iterable Type

The parameter must be either an array or an instance of Traversable:

function itrExample(iterable $itr) {
 foreach ($itr as $v) {
  echo "$v ";
 }
}

function test(){
 yield 'brain ';
 yield 'bell';
}

$itr = test();

itrExample($itr);