Friday, January 20, 2006

PHP5 parent:: Object

Working with PHP5 getting you used to work with real Object Orientatet Classes. Extended Classes or using the parent:: Object in such an extended Class is nothing new.

But i did not know (till now) that it is possible to jump over an extended Class to that parent.

To explain what i mean we have this Example:

class foo {
protected $iFoo = 0;
protected function bar() {
$this->iFoo++;
echo "foo: {$this->iFoo}
";
}
}
class fooA extends foo {
protected function bar() {
$this->iFoo++;
echo 'fooA:';
parent::bar();
}
}
class fooB extends fooA {
public function bar() {
$this->iFoo++;
echo'fooB';
parent::bar();
}
}

$oFoo = new fooB();
$oFoo->bar();

In this example we have 3 Classes, each extended by the next. Normally calling $oFoo->bar(); will output: "fooBfooA:foo: 3" which indicates that it starts with the latest class fooB, then runs through fooA to foo.

But what if you need an extend on fooA, but you don't want to run through it, you just want to run through fooB->bar and then foo->bar, without fooA?

I thought there is no solution for it, but there is! If you just change the function in fooB, where it says: "parent::bar();" to "foo::bar();" it will jump directly to foo, without fooA and it is not static as you may first think!

The Result will display: "fooBfoo: 2"

1 comment:

Anonymous said...

Yep, it's documented. In the past people were discussing if that's a good idea, because this basically means that if you try to call any static method, $this inside any static method is set to your current object. See the mix: any static method vs. your current object.