|
php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login |
[2017-07-16 22:17 UTC] vuk dot kulvar+php at gmail dot com
Description:
------------
When a parent class has a static method.
From the static method of the parent class, you can access protected methods & properties added from the child class.
I'm not talking about redeclaration, but methods & properties that doesn't exists in the parent class.
Test script:
---------------
class Alpha {
public static function Render($object) {
echo $foo->property;
echo $object->method();
}
}
class Omega extends Alpha {
protected $property = 'Property';
protected function method() {
return 'Method';
}
}
Alpha::Render(new Omega());
Expected result:
----------------
Fatal error: Cannot access protected property Omega::$property
Fatal error: Call to protected method Omega::method()
Actual result:
--------------
Property
Method
PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits
|
|||||||||||||||||||||||||||
Copyright © 2001-2025 The PHP GroupAll rights reserved. |
Last updated: Thu Oct 30 18:00:02 2025 UTC |
This is a consequence not of visibility, but of "duck typing". There is no difference in PHP between "redeclaration" or "overriding" and simply adding a new member - all lookups are dynamic at runtime. It may seem odd at first that a parent class can access protected members of a child class at all, but consider this pattern: class A { public function something() { // important logic $this->onSomethingHook($someEventData); // more important logic } protected function onSomethingHook($someEventData) { // No logic; extension point provided for sub-classes to add custom behaviour } } class B extends A { protected function onSomethingHook($someEventData) { // Custom logic here, which will be called from class A } } At a glance, you might say that A::something() is calling B::onSomethingHook(), but in fact the run-time behaviour would be identical if we declared A::onSomethingHook as abstract, or didn't declare it at all - as far as PHP is concerned, the lookup is against whatever $this resolves to at run-time. If we required a declaration of onSomethingHook in A (or its ancestors), would we also require it with a public member? If not, why not? class A { public function something() { $this->onSomethingHook($someEventData); } } class B extends A { public function onSomethingHook($someEventData) { // ... } }