update page now

Voting

: three minus one?
(Example: nine)

The Note You're Voting On

strata_ranger at hotmail dot com
15 years ago
I was recently extending a PEAR class when I encountered a situation where I wanted to call a constructor two levels up the class hierarchy, ignoring the immediate parent.  In such a case, you need to explicitly reference the class name using the :: operator.

Fortunately, just like using the 'parent' keyword PHP correctly recognizes that you are calling the function from a protected context inside the object's class hierarchy.

E.g:

<?php
class foo
{
  public function something()
  {
    echo __CLASS__; // foo
    var_dump($this);
  }
}

class foo_bar extends foo
{
  public function something()
  {
    echo __CLASS__; // foo_bar
    var_dump($this);
  }
}

class foo_bar_baz extends foo_bar
{
  public function something()
  {
    echo __CLASS__; // foo_bar_baz
    var_dump($this);
  }

  public function call()
  {
    echo self::something(); // self
    echo parent::something(); // parent
    echo foo::something(); // grandparent
  }
}

error_reporting(-1);

$obj = new foo_bar_baz();
$obj->call();

// Output similar to:
// foo_bar_baz
// object(foo_bar_baz)[1]
// foo_bar
// object(foo_bar_baz)[1]
// foo
// object(foo_bar_baz)[1]

?>

<< Back to user notes page

To Top