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

StackOverflow https://stackoverflow.com/questions/15561138

  •  29-03-2022
  •  | 
  •  

Question

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?

Was it helpful?

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

OTHER TIPS

An unconventional answer, but you really wanted to type hint for a string, you could create a new class for it.

class String
{
    protected $value;

    public function __construct($value)
    {
        if (!is_string($value)) {
            throw new \InvalidArgumentException(sprintf('Expected string, "%s" given', gettype($value)));
        }

        $this->value = $value;
    }

    public function __toString()
    {
        return $this->value;
    }
}

You can use it Javascript style

$message = new String('Hi, there');
echo $message; // 'Hi, there';

if ($message instanceof String) {
    echo "true";
}

Typehint example

function foo(String $str) {

}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top