PHP 7 and strict “resource” types

PHP does not have a type hint for resources because

No type hint for resources is added, as this would prevent moving from resources to objects for existing extensions, which some have already done (e.g. GMP).

However, you can use is_resource() within the function/method body to verify the passed argument and handle it as needed. A reusable version would be an assertion like this:

function assert_resource($resource)
{
    if (false === is_resource($resource)) {
        throw new InvalidArgumentException(
            sprintf(
                'Argument must be a valid resource type. %s given.',
                gettype($resource)
            )
        );
    }
}

which you could then use within your code like that:

function test($ch)
{
    assert_resource($ch);
    // do something with resource
}

Leave a Comment