How to use PHP Type Declarations

Last Updated on: September 16, 2022

PHP has developed into a more strictly typed language in recent years.

Type Declarations help with that and are a fairly new addition to PHP, with recent releases improving them further. They give you more precise, concise code, clarity, validation, type-hinting and more.

But first… what are Type Declarations? Take a look at this example:

function printMonkeysName(string $monkeysName) {
  echo $monkeysName;
}

printMonkeysName('Harold'); // Prints 'Harold'
printMoneysName(1010111); // Fatal Error

This function has specified the type it expects for the first parameter. This is a Type Declaration and gives you the following benefits:

  • More likely to catch type mismatch errors during coding
  • Enables easier and more automated testing
  • Your IDE will show you what the function expects (i.e. Type Hinting)
  • Your IDE will highlight type mismatch errors
  • Smaller PHP DocBlocks for less cluttered code (i.e. no need to specify types in comments)

We can take this example further and specify what the function will return:

function getMonkeysAge(array $monkey) : int {
  return $monkey['age'];
}

$myMonkey = [
  'name' => 'Benjamin',
  'age' =>,
];

echo getMonkeysAge($myMonkey); // Returns 7

In this example, we specified that the return value of the function is always going to be an integer. This helps to reduce DocBlock comments further and gives your IDE more helpful information.

Now, let’s go a step further and introduce multiple types and custom classes:

// Custom classes defined elsewhere
use App\Monkey;
use App\Tiger;

function describeAnimal(Monkey|Tiger $animal) : void {
  echo $animal->getName().' is a '.$animal->getType().' and is '.$animal->getAge().' years old.';
}

$myMonkey = new Monkey('Jenny', 3);
$myTiger = new Tiger('Brian', 22);

describeAnimal($myMonkey); // Jenny is a monkey and is 3 years old
describeAnimal($myTiger); // Brian is a tiger and is 22 years old

Hopefully, you can see the power of Type Declarations from this example.

Because we have strictly defined the type in our describeAnimal function, we can confidently rely on the methods getName, getType and getAge being available.

A good IDE will type-hint these methods for you – it will show you what methods and properties are available in your $animal property.

This saves time by catching any errors directly in your code.

Getting into the habit of using Type Declarations in PHP is a great way to clean up your code, reduce errors and increase maintainability for the future.


Get notified of new posts:


Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *