Search code examples
phpmethod-parameters

Why can't I pass a function that returns a string, as a parameter of a function, where the parameter is of type string?


Why can't I pass a function that returns a string, as a parameter of a function, where the parameter is of type string?

For example:

function testFunction(string $strInput) {
    // Other code here...
    return $strInput;
}

$url1 = 'http://www.domain.com/dir1/dir2/dir3?key=value';
testFunction(parse_url($url1, PHP_URL_PATH));

The above code returns an error:

Catchable fatal error: Argument 1 passed to testFunction() must be an instance of string...

How can I do this?


Solution

  • PHP type hinting does not support scalar types like strings, integers, booleans, etc. It only current supports objects (by specifying the name of the class in the function prototype), interfaces, arrays (since PHP 5.1) or callable (since PHP 5.4).

    So in your example PHP thinks you are expecting an object that is from, or inherits from, or implements an interface called "string" which is not what you're trying to do.

    PHP Type Hinting