1

Best to explain by example:

public function runRequest()
{
    $ch = curl_init();
    //.... Set Curl Options ....
    $response = curl_exec($ch);

    if ($response === false)
        throw new Exception('Boom! A feck, didnt close $ch');

    curl_close($ch);
}

Just wondering is this safe? will the $ch be handled properly.

If not, I can change $ch to be a class variable, and destroy in the destructor.

Thoughts? thanks in advance

4

2 回答 2

6

$ch will go out of scope and is thereby eligible for garbage collection. When that happens, the resource will be properly deallocated and closed. At least when the script execution ends, all resources will be properly disposed of. As such, it's not really necessary to close resources manually; but it's good practice to keep resource usage as low as possible, especially for long running scripts.

PHP 5.5 features try..catch..finally, which allows you to always close such resources even in the event of a thrown exception. (Which I just realized doesn't really apply to this situation though.)

于 2013-07-09T10:44:01.597 回答
1

You'll want to close the handle before throwing the exception.

if (!$response)
{
    curl_close($ch);
    throw new Exception('Boom! No response...');
}

When you throw an exception, it'll stop executing any more of your code in that section and bubble right up to where you catch it, else you'll get:

Fatal error: Uncaught exception

On the flip side, if you don't close the handle, it's not really that big of an issue. Just don't make a habit of it ;)

However, looking at your code again, your exception doesn't make sense. You will have closed it in this case...

于 2013-07-09T10:42:24.370 回答