Explanation of PHP class members visibility and inheritance

后端 未结 1 375
执笔经年
执笔经年 2021-01-19 02:43

Consider the following snippet:

Class A {

    private $a = \'foo\';

    public function F() {
        return $this->a;
    }

}

Class B extends A {

           


        
1条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-19 02:57

    From PHP: Visibility:

    Members declared protected can be accessed only within the class itself and by inherited and parent classes. Members declared as private may only be accessed by the class that defines the member.

    In your example, regardless of the object being of class B, class A cannot access a private property of another class.

    Also, if B has a protected property, that cannot override the class A property because it is private.

    Both your example and the following yield foo:

    Class A {
    
        private $a = 'foo';
    
        public function F() {
            return $this->a;
        }
    }
    
    Class B extends A {
    
        protected $a = 'bar';
    
        public function F() {
            return parent::F();
        }
    }    
    echo (new B)->F();
    

    However, if class A is also protected then it can be overridden by class B and class A has access to the property in class B.

    Yields bar:

    Class A {
    
        protected $a = 'foo';
    
        public function F() {
            return $this->a;
        }
    }
    
    Class B extends A {
    
        protected $a = 'bar';
    
        public function F() {
            return parent::F();
        }
    }
    echo (new B)->F();
    

    0 讨论(0)
提交回复
热议问题