1

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 ?

0

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

2 Comments

The only exception is array.
In other words: typehinging works for non-scalar types only.
1

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.