Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php object oriented visibility

I'm a little confused about this paragraph on OO visibilty in PHP. was curious if someone could explain it to me. examples would be GREAT! my brain is not thinking clear.

http://www.php.net/manual/en/language.oop5.visibility.php

The first paragraph reads

The visibility of a property or method can be defined by prefixing the declaration with the keywords public, protected or private. Class members declared public can be accessed everywhere. 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.

how can a parent class access a childs class member?

like image 944
veilig Avatar asked Apr 08 '11 01:04

veilig


2 Answers

That's how:

class A {
    public function test() {
        $b = new B;
        echo $b->foo;
    }
}

class B extends A {
    protected $foo = 'bar';
}

$a = new A;
$a->test();
like image 149
deceze Avatar answered Sep 27 '22 21:09

deceze


PHP is an interpreted language. Properties are resolved at runtime, not at the compiling stage. And access modifiers are just checked when a property is accessed.

It makes no difference if you ad-hoc inject a new (undeclared) property so it becomes public, or if you declare a protected property in an inherited class.

The private really only affects the accessibility from the outside. The ->name resolving at runtime works regardless of that. And the PHP runtime simply doesn't prope if the property declaration was made for the current object instances class. (Unlike for private declarations.)

like image 32
mario Avatar answered Sep 27 '22 21:09

mario