rfc:returntypehint2

This is an old revision of the document!


Request for Comments: Method Return Type Hints

Introduction

The purpose behind this RFC is to introduce return type hinting to PHP class methods. This RFC differs from the existing entry with a completely different concept and patch. The language changes taken by this approach is, in my opinion, more advantageous because it provides a more familiar interface to method type hinting and uses the existing standard created by parameter type hinting.

Syntactical Changes

Approach

Languages like C# and Java provide an elegant syntactical approach to defining this:

[method_attributes] [return_type] [method_name] '(' parameters ')'

When writing this patch, I saw no reason diverge from this direction. However, there was a caveat: PHP has the pseudo-type “mixed”, which doesn't actually have a keyword. To top this off, the existing definitions for methods require the keyword “function” in order for the language parser (zend_language_parser.y) to detect the entry. Making a change to the language requiring a return type hint would break compatibility and be completely unacceptable. Rather than this creating a challenge requiring a workaround, the BC issue actually resolved the issue! Keeping the existing declaration using “function” could serve as the mixed type and maintain BC.

Using Existing PHP Standards

With the introduction to the new object model in PHP 5 came parameter type hinting. Developers could define objects and arrays (as of version 5.1), forcing the caller to provide a precise type or face raising a catchable fatal error. This eliminated the need for functions and methods to constantly contain blocks of code verifying a provided value is a specific type. Moving this check to the Zend Engine not only made execution faster, but it also saved precious development time. This approach inherently provides valuable documentation and establishes confidence

Why do we need type hinting for methods?

Common Misconceptions

Proposal and Patch

Changelog

rfc/returntypehint2.1324095349.txt.gz · Last modified: 2017/09/22 13:28 (external edit)