Question

I'm trying to use this method :

public function setMessage(string $message){
    $this->message = $message;
}

Then I get this error :

Catchable fatal error: Argument 1 passed to notifier::setMessage() must be an instance of string, string given

Apparently PHP is interpreting string as class name. Is there a look like solution to make that kind of declaration ?

Was it helpful?

Solution

Typehinting can only be used on objects, with the exception of arrays.

From the Manual:

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

OTHER TIPS

PHP is a loosely typed language, it doesn't really care about the type and will guess anyways. You can only limit variables to classes at the function declaration, so remove the string and everything will be fine. :)

If you really want to be sure it is a string use gettype() or cast the variable to a string.

Note (from type-juggline on PHP.net):

Instead of casting a variable to a string, it is also possible to enclose the variable in double quotes.

$foo = 10;            // $foo is an integer
$str = "$foo";        // $str is a string
$fst = (string) $foo; // $fst is also a string
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top