This one really messes with my head:
Whenever I try to typecast a var passed to a function of type ‘string’, like this:
public function __call( string $name , array $args ) {
...
}
I get the following error:
Catchable fatal error: Argument 1 passed to [ClassName]::__call() must
be an instance of string, string given in [php_file_name] on line
[line_number]
Huh? “Must be an instance of string, string given”? Did I not pass a string? I seriously don’t understand this error message.
Now my solution has always been something like:
public function __call( $name , array $args ) {
if (!is_string($name)) { throw new Exception('$name must be a string');
}
However, my question, is there a way to actually typecast it in the method definition rather than inside the method itself?
In php you can force functions parameters to be either an array or an object (type hinting). So your action is only accepting “string” objects for the first argument, not variables of type string.
More info here: http://www.php.net/manual/en/language.oop5.typehinting.php
And to answer your question: Normally, you can’t!