Parameter declaration using file handle resource

In trying to make my PHP code less “loose”, I’m declaring parameter types on functions, like:

function len (string $str) :int 

What is the method for doing this when passing a file resource returned from fopen()? The PHP manual writes functions like:

function out (resource $fp,string $str)

But I get: PHP Warning: “resource” is not a supported builtin type and will be interpreted as a class name. Write “\resource” to suppress this warning…
Aside from just using \resource and suppressing the warning, is there a more correct way of declaring the parameter $fp in this example? I presume I might run into other similar situations? I’m not understanding the distinction between a builtin type versus a file handle or other similar structures, I guess.

Thanks.

Well that’s the way you’re supposed to do it if you put things into a class. You have to use the use keyword along with the class/namespace you’re trying to associate to. For instance if I have my own namespace like

<?php
namespace Foo;

class Bar {

	public function data(stdClass $data): void {
		print_r($data);
	}

}

I have to use \stdClass because PHP thinks the class stdClass is part of my script rather than a built-in class in PHP. So you’d have to do something like this.

<?php
namespace Foo;

use \stdClass;

class Bar {

	public function data(stdClass $data): void {
		print_r($data);
	}

}

The same is true about your situation as well. Since resource is a built-in class, you have to tell PHP that it’s not part of your class so PHP can then use the built-in class instead.

1 Like

Okay, though does it make a difference that my code isn’t using any class, I’m just trying to declare a function the old-fashioned way, and give the parameters a type definition as seems to be the way in PHP8?

You still have to tell PHP the class resource you’re trying to access isn’t a part of yours.

Gotcha. Thank you much!

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.