Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
303 views
in Technique[技术] by (71.8m points)

php 7 - PHP 7 and strict "resource" types

Does PHP 7 support strict typing for resources? If so, how?

For example:

    declare (strict_types=1);

    $ch = curl_init ();
    test ($ch);

    function test (resource $ch)
    {

    }

The above will give the error:

Fatal error: Uncaught TypeError: Argument 1 passed to test() must be an instance of resource, resource given

A var_dump on $ch reveals it to be resource(4, curl), and the manual says curl_init () returns a resource.

Is it at all possible to strictly type the test() function to support the $ch variable?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...