Problem with types in function parameter

Asked

Viewed 360 times

7

When executing 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, string Given, called in /home/...

I was intrigued because I had never done 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 be executed correctly?

I believe that this mistake should be better explained.

1 answer

6


According to the documentation:

Hinttype s can’t be used with scalar types such as int or string. Resources and Traits are not allowed either.

Simply put, you cannot force the parameter to the type string for being a scalar type that is not supported.


Note: This information is not Portuguese version of the manual, I don’t know why I thought it was important, but it says:

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

Which in a way also tells us that string is not included.


Editing:

To see if it’s a string according to the example you gave, only old-fashioned:

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 courtesy of @Luizvieira

  • 1

    OS(en) Question testifying to this answer: http://stackoverflow.com/questions/4103480/really-php-argument-1-passed-to-my-function-must-be-an-instance-of-string-s (There is even a string class suggestion to allow type-hint like this - I believe the previous, last answer)

  • I really thought PHP had a string class.

  • Implement a class String in PHP is very overhead. As there is no support for operator overload, you will depend on methods to do simple things like concatenation, etc.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.