php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Request #66886 extend type hint to base types, class members and variables
Submitted: 2014-03-12 07:57 UTC Modified: 2014-03-13 13:29 UTC
From: matteo_tassinari_TM at libero dot it Assigned:
Status: Wont fix Package: Unknown/Other Function
PHP Version: Irrelevant OS: Irrelevant
Private report: No CVE-ID: None
Have you experienced this issue?
Rate the importance of this bug to you:

 [2014-03-12 07:57 UTC] matteo_tassinari_TM at libero dot it
Description:
------------
I would like to suggest a new feature for a future version of PHP, for which I did not find any entry in the RFC wiki.

Basically, it could be useful to extend the type hinting for functions and methods also to standard PHP types (int, bool, float, etc.) and also allow for multiple acceptable types.

For example:

function foo(int|string $parameter = NULL) { ... }

Here $parameter MUST be one of NULL, int or string, or it would trigger a fatal error.

I think that the interpreter should not do any type juggling in this case, or only for the most simple and potentially less dangerous, for example bool to int, int to float or float to int (with warning in this case), but not for example string to int.

Also, the default value for a parameter should be consistent so that for example:

function bar(int $param = "") { ... }

would cause a fatal error too.

At the same way it could be useful to typehint variables and class properties, so that a "declaration" like:

int $i = 0;

would trigger a fatal error if, at any later point, $i is assigned something different than an integer, the same would apply to:

class C {
  public int $i = 0;
}

In this cases, it could be useful to have multiple hints too, like

class C {
  public int|string $xxx = 0;
}

And it would be up to the interpreter to enforce the type upon assignment.

There is already an RFC for allowing a type hint like "Class_Name_Here[]" for an array of a specific type, and that RFC could be extended also in this case, so that a type hint of "int[]" would be acceptable.

Lastly, such new feature should be completely backward compatible, as it would be optional to use it, and there cannot be any current code like that.

Test script:
---------------
See description


Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2014-03-13 01:43 UTC] rasmus@php.net
-Status: Open +Status: Wont fix
 [2014-03-13 01:43 UTC] rasmus@php.net
You are suggesting we turn a loosely typed language into a strongly typed one. Won't happen.
 [2014-03-13 13:29 UTC] matteo_tassinari_TM at libero dot it
That's not exactly correct, it would remain something a developer COULD do, not something the developer MUST do.
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Thu Apr 25 17:01:29 2024 UTC