Stop Using Pseudo-Types
7 days ago
- #PHP
- #Programming
- #Best Practices
- Pseudo-types like 'callable' and 'iterable' in PHP are not true types but sets of types with specific validation logic.
- The 'callable' pseudo-type includes types like 'Closure', 'string', and 'array' with runtime validation for callability.
- The 'iterable' pseudo-type was introduced in PHP 7.1 and later became a union type 'Traversable|array' in PHP 8.2.
- Using 'iterable' for return types can lead to confusion and misuse, as it may return either an array or an iterator.
- For better code clarity and analysis, prefer explicit types like 'Closure' over 'callable' and generators over 'iterable'.
- Typing properties with 'Closure' requires specific syntax for invocation, such as '($this->callback)();' or '$this->callback->__invoke();'.
- Avoiding pseudo-types improves code readability, reduces errors, and enhances compatibility with static analyzers like PHPStan.