apokryfos
apokryfos

Reputation: 40730

Accessing child protected members from parent

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)?

Upvotes: 2

Views: 680

Answers (3)

vz0
vz0

Reputation: 32933

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.

Upvotes: 0

dinnbot
dinnbot

Reputation: 64

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.

Upvotes: 1

Conyc
Conyc

Reputation: 460

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.

Upvotes: 2

Related Questions