Invoking the calling class in a static inherited environment

In PHP, if you have a number of  static classes, how do you make sure the called class ends up calling a method back in the calling class?

It's a complicated question, so let me clarify it with an example. Let's say I have the following classes:

Pet
  Dog (extends Pet)
    Newfoundland (extends Dog)
  Cat (extends Pet)
    MaineCoon (extends Cat)

All are used as simpletons, i.e. only one occurence, and because of this, the decision has been made to use all statically: no instantiation. So, if there is a method in Pet that is not implemented elsewhere, say, Pet::petname(), and at some point it needs to make call to ::petTags(), which is overridden in each class, if Pet::petName() is called by MaineCoon, how do we make sure that from Pet::petName() we end up calling MaineCoon::petTags()? 

There are a number of options, but if your version of php is 5.3 or greater, make use of the static keyword. It will call the calling class. 

A quick example:

class a {

  protected static function p() {

    print 'rocky';

  }

  protected static function test() {

    static::p();

  }

}

class b {

  protected static function p() {

    print 'bullwinkle';

  }

  public function showMe() {

    self::test();

  }

}

b::showMe() yields bullwinkle. The static::p() in class a calls b::p(), because class b was the class that called a::test()

Add new comment

Plain text

  • No HTML tags allowed.
  • Web page addresses and email addresses turn into links automatically.
  • Lines and paragraphs break automatically.
Of course, the Drupal Community isn't the only place to give back. It's a complex world, and there are as many worthy causes as their are melodies, with most being served by multiple charitable organizations. Here are a few of those that strike a 7th chord with me.