Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

extending static methods in php

Tags:

php

static

class Foo {
  public static function foobar() {
    self::whereami();
  }

  protected static function whereami() {
    echo 'foo';
  }
}

class Bar extends Foo {
  protected static function whereami() {
    echo 'bar';
  } 
}

Foo::foobar();
Bar::foobar();

expected result foobar actual result foofoo

to make matters worse, the server is restricted to php 5.2

like image 952
Bruce Aldridge Avatar asked Sep 27 '26 03:09

Bruce Aldridge


1 Answers

All you need is a one-word change!

The problem is in the way you call whereami(), instead of self:: you should use static::. So class Foo should look like this:

class Foo {
  public static function foobar() {
    static::whereami();
  }
  protected static function whereami() {
    echo 'foo';
  }
}

In another word, 'static' actually makes the call to whereami() dynamic :) - it depends on what class the call is in.

like image 197
Tony Jiang Avatar answered Sep 28 '26 22:09

Tony Jiang



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!