Type hinting in PHP 7 - array of objects

后端 未结 7 1881
迷失自我
迷失自我 2020-12-08 03:36

Maybe I missed something but is there any option to define that function should have argument or return for example array of User objects?

Consider the following cod

7条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-08 04:30

    As arrays can contain mixed values this is not possible.

    You have to use an objects / class for that purpose.

    You could create a class that will manage its own list array (private/protected attribute) and deny adding other values as a workarround for this issue if this is really needed.

    However no responsible programmer will ever break the intended pattern, especially not if you comment it correctly. It will be recognized in occuring errors in the program anyway.

    The exaplanation:

    For example you can create any array:

    $myArray = array();
    

    and add a number:

    $myArray[] = 1;
    

    a string:

    $myArray[] = "abc123";
    

    and an object

    $myArray[] = new MyClass("some parameter", "and one more");
    

    Also do not forget that you can have a simple array, a multi-dimensional stacked array and also associative arrays which can have mixed patterns aswell.

    Its pretty hard till impossible to found a parser/nottation to make all that versions work with an expression that forces the format for an array I think.

    It would be cool on the one side but on the other side of the medal you would loose some ability to mix data within an array which could be crucial to alot of existing code and the flexibility PHP has to offer.

    Because of the mixed content which feature we do not want to miss in PHP 7 it is not possible to type-hint the exact contents of an array as you can put inside anything.

提交回复
热议问题