Problem with types in function parameter

7

When you run the following code:

function foo(string $text) {
    echo $text;
}
foo('bar');

I get the following error:

  

PHP Catchable fatal error: Argument 1 passed to foo () must be an instance of string, given string, called in / home /...

I was intrigued because I had never done it before with Strings , I always did with Array , and it worked.

Question
The error occurred because the method called for an instance of string , but 'bar' is not an instance of string ? If 'bar' is not an instance of string , what parameter should I put in order for this function to execute correctly?

I think this error should be better explained.

    
asked by anonymous 24.01.2014 / 01:33

1 answer

6

According to documentation :

  

Type hints can not be used with scalar types such as int or string . Resources and Traits are not allowed either.

Simply put, you can not force the parameter to type string because it is a scalar type that is not supported.

Note: This information does not appear in Portuguese version of the manual , I do not know why it's important, but it says:

  

... Functions can force parameters to be objects ... or array ...

That somehow also tells us that string is not included.

Issue:

To check if it is a string as the example you gave, just old fashion :

function foo($text) {
    if (is_string($text))
        echo $text;
    else
        echo "Aqui só strings amigo!";
}

Or as seen in the topic whose link (English) was placed in the comments:

function foo($text) {
    if (!is_string($text)) {
        trigger_error('No, you fool!');
        return;
    }
    ...
}

Link was courtesy of @LuizVieira

    
24.01.2014 / 01:59