6

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?

5
  • PHP does not support type-hinting for the standard data types (int, doubles), but does support type-hinting of objects. Commented Jan 10, 2013 at 13:46
  • Sure - I read that too - so what's the solution? Commented Jan 10, 2013 at 13:47
  • 1
    remove 'int' from public function setPersonId(int $value) Commented Jan 10, 2013 at 13:48
  • read this: ch2.php.net/language.oop5.typehinting Commented Jan 10, 2013 at 13:52
  • As I mentioned, I've read this. Commented Jan 10, 2013 at 13:53

3 Answers 3

14

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
    }
}
Sign up to request clarification or add additional context in comments.

4 Comments

Sure, I read this - but how can you then handle that? You can not convert? Are we saying the value needs to be int from the start or nothing.
If you want the value to be an int, but is_int returns false, you could cast it $value = (int) $value;. If you don't care if it's an int or not, just remove the is_int check.
This is pretty horrid, but admittedly seems the only way to go. PHP doesn't get it :/
In PHP 7, type hinting (now called type declaration) allows specifying scalar types too, see php.net/manual/en/…
-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

Comments

-3

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

private int $personId;

instead of

private integer $personId;

1 Comment

You are not in PHP, aren't you?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.