返回资源的无辜PHP函数?

Some PHP functions, like fopen(), have a return value of type "resource".

However, most of these functions require some actual outside resource, such as a file or database. Or they require additional PHP extension to be installed, such as curl_open().

I sometimes want to experiment with different value types on https://3v4l.org, where I cannot rely on external resources.

Another scenario where this might be relevant is unit tests, where we generally want as little side effects as possible.

So, what is the simplest way to get a value of type resource, without external side effects, 3rd party extensions, or external dependencies?

You can use php://memory or php://temp as resource. The first one doesn't even need access to the system /tmp folder.

Example:

$resource = fopen('php://temp', 'w+');

The best I've come up with so far is tmpfile().

It does work in https://3v4l.org/00VlY. Probably they have set up some kind of sandbox filesystem.

$resource = tmpfile();
var_dump(gettype($resource));
var_dump($resource);
var_dump(intval($resource));

I would say it is still not completely free of side effects, because it does something with a file somewhere. Better ideas are welcome!

I use

fopen('php://memory', 'w'); or fopen('php://temp', 'w'); when I just need a file stream resource to play with.

php://temp is better if the buffer will exceed 2mb.