2

I've noticed that in PHP the following code works with no complaints:

class A {            
    public static function echoes($b) {
        echo $b->protectedFunction();
    }        
}

class B extends A {
    protected function protectedFunction() {
        return "this is protected";
    }
}

$b = new B();
A::echoes($b);

Example https://3v4l.org/JTpuQ

However I've tried this in C# and it does not work as the parent cannot access the child protected members.

My question is who's got the OOP principles right here? I've read through the LSP but it doesn't seem concerned with parent classes, so is it correct for a parent to access child protected members (like PHP assumes it is) or should it be restricted (like C# assumes it should be)?

apokryfos
  • 38,771
  • 9
  • 70
  • 114
  • 3
    Note the PHP docs explicitly include this case: "Members declared protected can be accessed only within the class itself and by inheriting *and parent* classes." – Alex Howansky Apr 05 '18 at 14:27

3 Answers3

2

The way that C# restricts access seems to be the most logical way to do it.

A parent should not be able to inherit anything from a child. And without inheriting anything from the child, the parent should not have access to the child's protected methods.

Conyc
  • 460
  • 1
  • 4
  • 10
  • 1
    But the parent isn't *inheriting* anything -- he's not calling `$parent->protected()`, he's calling `$child->protected()`. Weird case. I can see it going either way. – Alex Howansky Apr 05 '18 at 14:21
  • @AlexHowansky That is exactly my point. Since the parent isn't inheriting anything from the child, it should not be inheriting the child's access to the protected method either. – Conyc Apr 05 '18 at 14:27
1

I think you might get problems letting the parent know something about the children. Because parents are used to extract and bundle behavior and attributes from multiple classes, so the way of information is just in one direction.

Maybe there are cases in which you need to access the protected attributes, but I guess wherever it is not needed avoid it.

kajetons
  • 4,481
  • 4
  • 26
  • 37
dinnbot
  • 64
  • 5
0

PHP is a dynamically typed language. Function and method calls are not checked until that line of code is actually executed. In PHP you can have two objects instances from the same class with different methods. This works fine.

Statically typed languages like C# require to know the types of objects before execution. You can still use reflection to call children methods from the parent, but you can't add new methods dynamically.

vz0
  • 32,345
  • 7
  • 44
  • 77
  • Here's what bugs me though. https://3v4l.org/uhWNS does not work because the child method is private. To me this makes PHP treat protected methods as accessible from parent and child classes so I don't think this is an artefact of the the dynamic typing – apokryfos Apr 05 '18 at 15:28