开发者

Strong data typing bug

开发者 https://www.devze.com 2022-12-09 05:11 出处:网络
Is it normal to get the error \"Default value for parameters with a class type hint can only be NULL\" for a method in an interface defined as

Is it normal to get the error "Default value for parameters with a class type hint can only be NULL" for a method in an interface defined as

public function nullify(bool 开发者_StackOverflow社区$force=FALSE);

?

I need it to be bool, not an object, and FALSE by default.


There is no type hinting for boolean parameters in php (yet). You can only specify a class name or array. Therefore function foo(bool $b) means: "the parameter $b must be an instance of the class 'bool' or null".

http://docs.php.net/language.oop5.typehinting:

Functions are now able to force parameters to be objects (by specifying the name of the class in the function prototype) or arrays (since PHP 5.1).


As already stated, type hinting only works for arrays and object. Your function can be written like this:

public function nullify($force=FALSE){
  $force=(bool)$force;
  //further stuff
}


PHP 5 type hinting is limited to a specific class (or one of its subclasses), or an array. You cannot specify any other scalar types.


You can't force a parameter to be a boolean.

As found in language.oop5.typehinting :

PHP 5 introduces type hinting. Functions are now able to force parameters to be objects [...], interfaces, arrays (since PHP 5.1) or callable (since PHP 5.4).

[...]

Type hints can not be used with scalar types such as int or string. [...]

And as found in language.types.intro, PHP scalar types are :

- boolean
- integer
- float (floating-point number, aka double)
- string


You could try:

public function nullify($force){
  if(is_object($force)) $force = false;
  ...
}

Consider it as a temporary solution until you upgrade PHP.

0

精彩评论

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

关注公众号