PHP: Converting integer to int - getting error

送分小仙女□ 提交于 2019-12-23 10:28:31

问题


I understood there wasn't much, if any different between int and integer in PHP. I must be wrong.

I'm passing a integer value to a function which has int only on this value. Like so:-

$new->setPersonId((int)$newPersonId); // Have tried casting with (int) and intval and both

The other side I have:-

    public function setPersonId(int $value) {
        // foobar
    }

Now, when I run - I get the message:-

"PHP Catchable fatal error: Argument 1 passed to setPersonId() must be an instance of int, integer given"

I have tried casting in the call with (int) and intval().

Any ideas?


回答1:


Type hinting in PHP only works for objects and not scalars, so PHP is expecting you be passing an object of type "int".

You can use the following as a workaround

public function setPersonId($value) {
    if (!is_int($value)) {
        // Handle error
    }
}



回答2:


To explicitly convert a value to integer, use either the (int) or (integer) casts. However, in most cases the cast is not needed, since a value will be automatically converted if an operator, function or control structure requires an integer argument. A value can also be converted to integer with the intval() function.

http://php.net/manual/en/language.types.integer.php




回答3:


Make sure that PersonID property is defined as int not integer:

private int $personId;

instead of

private integer $personId;


来源:https://stackoverflow.com/questions/14259327/php-converting-integer-to-int-getting-error

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!