Skip to content
Advertisement

PHP method scope binding

I am confused by how PHP call method in parent-children hierarchy. Here is the code

JavaScript

The output is A!

consider another example, but only change the foo() method visibility in class A to be public.

JavaScript

This output is C!

Any explanation is welcome.

Advertisement

Answer

Rule: private and final methods on an object will always be called directly, without consulting the override table.

This rule is baked into the engine:

JavaScript

“Why”, you ask? The answer is: because that’s how it works. In language design, this is called “name hiding”, and it’s up to the language to specify how name hiding works. Take C++ for example. It has well-defined, and complex name hiding rules. PHP has its own rules. They’re different from C++. But they’re unique to PHP. This is just something you have to memorize about the language.

I admit the docs could better spell this out, however.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement