PHP quiz #4 - hoistingJune 16, 2019
What will this code output?
- A Fatal error: Uncaught Error: Call to undefined function helloWorld()
- B Nothing
- C Hello World!
- D Warning + "helloWorld()"
AnswerShow the answer
Restrictions on hoisting
When the function is defined conditionally, this is not the case. For hoisting to work, it has to be defined on the top level. The following will throw a fatal error:
What about includes?
Naturally, they are only resolved at runtime. When including a function, the include statement must run before the function call.
Functions are not the only unit of code organization (thank God!).
Hoisting applies to class, interface and trait declarations too. More or less.
It becomes less graceful when multiple levels of inheritance is introduced.
It's not that big of a problem though.
Avoiding top level functions and declaring one class per file is considered as best practice. This eliminates the possibility of ever relying on PHP to hoist your code.
This post is part of a series based on a presentation I gave on March 20, 2019.