1

In PHP you can do the following thing:

class Something {// bla bla}

function functionName(Something $object) {
    // Do stuff here  ^^^^^^^^^
}

This ensures that function received an instance of Something class.

My problem is that I want to enforce to a basic type.

function functionName(integer $someInt) {
    // Do stuff here  ^^^^^^^
}
functionName(5);

This says that $someInt is "not an instance of integer, integer given" (with my PHP version below 7.0). How can you enforce to a basic type?

2
  • there's no integer keyword in php Commented Mar 20, 2015 at 14:46
  • you can simply add $someInt = (int)$someInt; on the first line of your function. this way you will always get an integer argument format. Commented Mar 20, 2015 at 14:56

2 Answers 2

7

You can't do this for scalar types see the manual:

And a quote from there:

Type hints cannot be used with scalar types such as int or string. Resources and Traits are not allowed either.

But you will be able to to this with PHP 7: https://wiki.php.net/rfc/scalar_type_hints_v5

Sign up to request clarification or add additional context in comments.

4 Comments

@jeroen Thanks!, was just going to add it with a quote :D
@Rizier123 Sounds promising that PHP 7 will support that. I've asked multiple times for that feature, but always got an answer like you don't need to typehint scalar types if you understand dynamically typed languages.. Hihi, seems I got it right! :D
@hek2mgl yeah there was a few attempts/proposal for this, but I think it will get added. (Didn't know about the SPlInt also an interesting way ;D)
Yeah, interesting. More interesting it would be if PHP would support a magic method __toInt() like __toString(). There is also an RFC for that.
7

You can't typehint scalar types in PHP. The only chance is to use a wrapper type. The SPL library ships with SplInt for that purpose.

Update: Looks like PHP 7 offers that feature. Sigh, times changed :)

Comments

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.