简体   繁体   English

从家长访问受儿童保护的成员

[英]Accessing child protected members from parent

I've noticed that in PHP the following code works with no complaints: 我注意到在PHP中,以下代码可以正常运行:

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 示例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. 但是,我已经在C#中尝试了此操作,但由于父级无法访问受子级保护的成员,因此无法正常工作。

My question is who's got the OOP principles right here? 我的问题是谁在这里拥有OOP原则? 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)? 我已经阅读了LSP,但是它似乎与父类无关,因此父访问子级受保护的成员是否正确(如PHP假定是这样)还是应该对其进行限制(如C#认为应该如此)? ?

The way that C# restricts access seems to be the most logical way to do it. C#限制访问的方式似乎是最合乎逻辑的方式。

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. 而且,如果不从子级继承任何东西,则父级不应有权访问子级的受保护方法。

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. 也许在某些情况下,您需要访问受保护的属性,但是我想在不需要的地方都避免使用它。

PHP is a dynamically typed language. PHP是一种动态类型的语言。 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. 在PHP中,您可以使用不同的方法从同一个类中获得两个对象实例。 This works fine. 这很好。

Statically typed languages like C# require to know the types of objects before execution. 像C#这样的静态类型语言要求在执行之前知道对象的类型。 You can still use reflection to call children methods from the parent , but you can't add new methods dynamically. 您仍然可以使用反射从父级调用子级方法 ,但不能动态添加新方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM