开发者

Type hinting in function argument (magic __call) throw exception

开发者 https://www.devze.com 2023-04-03 19:30 出处:网络
This one really messes with my head: Whenever I try to typecast a var passed to a function of type \'string\', like this:

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 solut开发者_如何学Goion 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.

Type Hints can only be of the object and array (since PHP 5.1) type. Traditional type hinting with int and string isn't supported.

More info here: http://www.php.net/manual/en/language.oop5.typehinting.php

And to answer your question: Normally, you can't!


PHP doesn't support scalar type-hinting. Only for objects and arrays. Someone at the PHP-comments has written a way to use scalar type-hinting. Because this error is of the type catchable fatal error. You can define your own error handler which lets you continue from this error in certain conditions.

http://www.php.net/manual/de/language.oop5.typehinting.php#83442

However, it's quite slow and I don't recommend using it.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号