Reputation: 40683
I'm not sure if this is a bug or I'm doing something wrong but consider the following code:
ParentClass.php
<?php
class ParentClass {
public static function getA() {
$obj = new ChildClass();
return $obj->a();
}
}
ChildClass.php
<?php
class ChildClass extends ParentClass {
protected function a() {
return "a";
}
}
However PhpStorm is showing an error in ParentClass.php
on line return $obj->a();
saying:
Member has protected access
The manual says that:
Members declared protected can be accessed only within the class itself and by inheriting and parent classes.
Is this a PhpStorm bug? If so is there a way to disable this error (for affected files ideally but globally would also do in a pinch).
Sidenote: I'm not discussing whether this is coding practices that should be followed but the actual problem is deep within legacy code I am very reluctant to modify and is causing my project navigation bar to fill up with squiggly red lines all over to indicate errors (which are not actual errors).
Upvotes: 4
Views: 5466
Reputation: 32310
I can reproduce this with phpStorm 2018.1.
Either this is a bug in phpStorm or this is just a warning by phpStorm because even tho it is possible in PHP to access a protected member this way, one should be warned because it is a thing you should probably avoid.
Because it is confusing, to access a protected/private member outside the scope.
The explanation is here http://php.net/manual/en/language.oop5.visibility.php#language.oop5.visibility-other-objects
Objects of the same type will have access to each others private and protected members even though they are not the same instances. This is because the implementation specific details are already known when inside those objects.
Both of your classes are instanceof ParentClass
so both can access each others protected and private members.
As LazyOne pointed out, there actually are bugs in phpStorm concerning this and similiar effects: https://youtrack.jetbrains.com/issue/WI-11263
Upvotes: 1
Reputation: 952
The ParentClass cannot access the child's a() method because it the parent class does not have that function, it is not inheriting that function, and it's protected so you can't call it from outside it's class or a class derived from ChildClass.
If you had a() defined in the ParentClass, then you could make the function getA() in the ChildClass and then it would have access to a()
Upvotes: 0