PHP 7.2 and Object Typehint

|2 min read|
Teklog
Teklog


Introduction

PHP 7.2 is around the corner.  On the 26th of October 2017, the 5th version of PHP Release Candidate has been announced, which was preceded by 3 alpha, 3 beta and 4 RC versions. First alpha version was announced on the 8th of June 2017 and the final version is about to be released by the end of November 2017.

If you are impatient and curious as I am, it's right time to take a sneak peak at what PHP team is cooking for us. You can track all implemented features by studying PHP Request For Comments wiki page.

Without further ado, let's explore the first feature together, an amazing Object Typehint

Assumptions

Try it yourself

Clone blogging-phplatest repository

git clone https://github.com/tekmi/blogging-phplatest
cd blogging-phplatest

Run docker container, based on the php 7.2.0 RC5 image.

docker run -it --rm \
-v "$PWD":/usr/src/php-7.2 \
-w /usr/src/php-7.2 \
php:7.2.0RC5-cli-stretch \
php php-7.2/object_typehint/index.php

Update Dec 2017: If you experience problems with image php:7.2.0RC5-cli-stretch, try php:7.2.0-cli-stretch instead.

Explanation

PHP 7.0 introduced scalar types for parameters as well as return types. PHP 7.1 on top of this added Nullable types, however there was still not possible to typehint objects.

PHP 7.2 for the rescue - it will soon be possible to use new object typehint as shown below:

function moves(object $obj): string
{
  return get_class($obj);
}

If you pass string, null or anything else that is not an object, you will encounter fatal error similar to: Fatal error: Uncaught TypeError: Argument 1 passed to moves() must be an object, string given

On the other hand, if you pass valid objects, as presented below, everything will work like a charm.

moves(json_decode('{}'))
moves(new \stdClass())
moves(new class() {})

How did we do it until now

Most probably parameter $obj won't be type-hinted (if we intend to accept scalars and objects) and we should check for an object - otherwise get_class would fire: Warning: get_class() expects parameter 1 to be object, string given

function moves($obj): string
{
  return is_object($obj) ? get_class($obj) : '';
}

Summary

By using object typehint, code should be easier to understand and errors detected quicker. It's a great addition to PHP language which I'm awaiting with impatience.