I realized something odd about accessing protected properties the other day. It's possible in PHP to access protected properties from other objects, as long as they are from the same class, as illustrated here:
<?php
class MyClass {
protected $val;
function __construct($newVal = 'default') {
$this->val = $newVal;
}
function output(MyClass $subject) {
echo $subject->val, "\n";
}
}
$obj1 = new MyClass();
$obj2 = new MyClass("hello world");
$obj1->output($obj2);
// Output: hello world
?>
I always thought that protected strictly allows objects to access things from the current inheritence tree, but didn't realize that this also extends to other instances of the same object.
This behavior works for properties and methods, and also when they are defined as private.
The other day, I realized though that this even works for objects of other classes, as long as you are accessing members that are defined in a class that also appears in the accessing class' ancestry.
Sounds a bit complicated, so here's the example:
<?php
class Ancestor {
protected $val = 'ancestor';
}
class Child1 extends Ancestor {
function __construct() {
$this->val = 'child1';
}
}
class Child2 extends Ancestor {
function output(Ancestor $subject) {
echo $subject->val, "\n";
}
}
$child1 = new Child1();
$child2 = new Child2();
$child2->output($child1);
// Output: child1
?>
Interestingly, if the last example is modified so that the properties are not set in the constructors, but instead by overriding the property, this will
Truncated by Planet PHP, read more at the original (another 3607 bytes)
more
{ 0 comments... » Accessing protected properties from objects that share the same ancestry. read them below or add one }
Post a Comment