DEV Community

Discussion on: How PHP Type Declarations Actually Work

Collapse
 
clabinger profile image
Cooper Labinger • Edited

I think you got the per-file basis backwards: strict types must be declared in the file calling the function, not the file where the function is defined.

From the PHP manual:

Strict typing applies to function calls made from within the file with strict typing enabled, not to the functions declared within that file. If a file without strict typing enabled makes a call to a function that was defined in a file with strict typing, the caller's preference (weak typing) will be respected, and the value will be coerced.

See php.net/manual/en/functions.argume...

Sadly, I think this partly defeats the purpose of enforcing types, since having to remember to declare strict types in each file that calls a function is not that different from just getting the function calls right in the first place.

Collapse
 
robdwaller profile image
Rob Waller

Yes what the manual says is sort of right on parameter types. If you don't declare strict types then the calling code will fall back to type coercion and not impose the parameter types defined in the required file. But if it can't coerce to the defined parameter type the code will still fail.

I've updated the associated GitHub library to highlight this point. github.com/RobDWaller/type-declara...

The article itself though is still technically correct it's just it is focused on return types and the fact you can't trust what you receive from a method without strict types imposed. I should maybe have stressed this point more.

I agree though that PHP Types aren't ideal but do believe they still have value when used correctly, you just have to impose strict types everywhere. 😂