PHP 7.2 and Object Typehint


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


Try it yourself

Clone blogging-phplatest repository

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

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


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:

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.

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 


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.

If you enjoyed this post, then make sure you subscribe to my Newsletter