Why Can't PHP Attributes Utilize Functions?
In PHP, attribute default values cannot incorporate function calls, a restriction that may raise questions about its implementation. This article delves into the technical underpinnings of this design choice.
Rationale
The compiler code indicates that this limitation is intentional, but its reasoning is undisclosed. Examining the compilation process provides some insight.
Compilation Process
When parsing class variable declarations, the compiler follows a specific grammar. Assignments must adhere to static scalar definitions. Arrays within these definitions must also contain static scalars.
If the grammar allowed non-static arrays, the code would pass syntax checks. However, it would result in a "Invalid binding type" compile error during the early binding stage, which ensures that the last opcode on the current array matches specific types.
Problematic Opcodes
When assigning non-static arrays, the compiler generates additional opcodes, such as INIT_ARRAY and DO_FCALL. These opcodes cause a mismatch during early binding, triggering the error.
Possible Solutions and Implementation Challenges
Other dynamic languages handle such scenarios. Potential solutions for PHP include:
Implementing these solutions would require careful consideration and non-trivial changes to the compiler.
Conclusion
The inability to use functions in PHP attributes stems from design decisions within the compilation process. While this may seem like a limitation, it appears to have been a conscious choice by the language designers. Implementing alternative solutions would require significant restructuring of the compilation process, which may not be deemed a priority.
The above is the detailed content of Why Can\'t PHP Attributes Support Function Invocation?. For more information, please follow other related articles on the PHP Chinese website!