Error when passing string into method with type hinting

后端 未结 5 2073
北荒
北荒 2020-12-20 11:11

In the code below I call a function (it happens to be a constructor) in which I have type hinting. When I run the code I get the following error:

Catchable fatal

相关标签:
5条回答
  • 2020-12-20 11:46

    From the PHP documentation (http://php.net/manual/en/language.oop5.typehinting.php)

    Type Hints can only be of the object and array (since PHP 5.1) type. Traditional type hinting with int and string isn't supported.

    No way to hint strings, ints or any other primitive type

    0 讨论(0)
  • 2020-12-20 11:53

    Type hinting can only be used for object data types (or arrays since 5.1), not for the basic types like string, integer, float, boolean

    0 讨论(0)
  • 2020-12-20 11:54

    Just remove string from constructor (not supported) , it should work fine eg:

    function __construct($anAnswer)
    {
       $this->theAnswer = $anAnswer;
    }
    

    Working Example:

    class Question
    {
       /**
        * The answer to the question.
        * @access private
        * @var string
        */
       public $theAnswer;
    
       /**
        * Creates a new question with the specified answer.
        * @param string $anAnswer the answer to the question
        */
       function __construct($anAnswer)
       {
          $this->theAnswer = $anAnswer;
       }
    }
    
    $question = new Question("An Answer");
    echo $question->theAnswer;
    
    0 讨论(0)
  • 2020-12-20 11:57

    PHP doesn't support type hinting for scalar values. Currently, it's only possible for classes, interfaces and arrays. In your case, it's expecting an object that is an instance of a "string" class.

    There is currently an implementation supporting this in the SVN trunk version of PHP, but it's undecided if that implementation will be the one that gets released in future versions of PHP, or if it will be supported at all.

    0 讨论(0)
  • 2020-12-20 11:57

    NOTE

    "type declarations" (aka "type hinting") are available for the following types since PHP 7.0.0:

    • bool The parameter must be a boolean value.
    • float The parameter must be a floating point number.
    • int The parameter must be an integer.
    • string The parameter must be a string.
    • bool The parameter must be a boolean value.

    for the following types since PHP 7.1.0:

    • iterable The parameter must be either an array or an instanceof Traversable.

    So from now on another answer to this question actually is (kind of):

    Switch the PHP version to PHP7.x and the code will work as you expect.

    http://php.net/manual/en/functions.arguments.php#functions.arguments.type-declaration

    0 讨论(0)
提交回复
热议问题