php_nub_qq
php_nub_qq

Reputation: 16065

PHP OOP access of protected members

Example code

class Example {

    protected $data = 'data ';

    public function getData() {
        return $this->data;
    }

    public function mergeWith(Example $e) {
        $this->data .= $e->data;
    }

}

$e1 = new Example();
$e2 = new Example();

$e1->mergeWith($e2);

Result is

Example Object
(
    [data:protected] => data data 
)

My question is - why am I able to access the protected/private properties of an object from outside the object? It is the same class but it is a different instance, shouldn't that count as an outside call? What is the idea behind this?

Upvotes: 0

Views: 40

Answers (1)

zerkms
zerkms

Reputation: 255155

The visibility is defined in terms of class hierarchy, not instances. So protecteds are accessed by all instances of the same hierarchy. So any object that is instaceof Example can access it.

That works the same way in pretty much every other (?) programming language that implements similar object model. Just out of the top of my head: C++ (with some exceptions, but in general it's still applicable here), C#, Java.

Upvotes: 1

Related Questions