简体   繁体   中英

When type hinting a class in PHP, do you need to include the class file?

If I have a class Foo and a function bar

function bar (Foo $x) { baz($x); }

that uses Foo as a type hint... do I need to include the file containing Foo in order for the above to compile?

In a test with PHP 5.4.33, including the class was not required, even when calling the function. The function failed, since the provided $x was not of type Foo , but no error such as "Error: Foo not defined" occurred.

Is this behavior dependable? Is it documented anywhere?

As a side note, I know that it could be good for documentation to include the Foo.php file when I'm using Foo as a type hint, but it does prevent a call to require_once if I don't have to include it.

All PHP does is check the name of the type. It does not link it to any concrete implementation. As such, it is not required in any way to have access to a concrete implementation of that type; meaning you do not need to include the file which defines the type.

This is not an authoritative response.

I can imagine that PHP objects internally have a field where the class name is stored. This could be used for the argument check.

In the case where the object is a valid instance of Foo (and you want to use it) you will already need the definition of Foo else you can't make an instance.

So it seems like the argument check doesn't need the definition of Foo .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM