3
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

Marco Demaio
  • 33,578
  • 33
  • 128
  • 159
Bruce Aldridge
  • 2,907
  • 3
  • 23
  • 30
  • 2
    PHP 5.3 introduced [late static bindings](http://php.net/manual/en/language.oop5.late-static-bindings.php). Looks like you might be out of luck with 5.2 – Phil May 02 '11 at 04:10

3 Answers3

9

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.

Tony Jiang
  • 442
  • 5
  • 16
1

Try to use singleton pattern:

<?php

class Foo {
    private static $_Instance = null;

    private function __construct() {}

    private function __clone() {}

    public static function getInstance() {
        if(self::$_Instance == null) {
            self::$_Instance = new self();
        }
        return self::$_Instance;
    }

    public function foobar() {
        $this->whereami();
    }

    protected function whereami() {
        print_r('foo');
    }
}
class Bar extends Foo {
    private static $_Instance = null;

    private function __construct() {}

    private function __clone() {}

    public static function getInstance() {
        if(self::$_Instance == null) {
            self::$_Instance = new self();
        }
        return self::$_Instance;
    }

    protected function whereami() {
        echo 'bar';
    } 
}

Foo::getInstance()->foobar();
Bar::getInstance()->foobar();


?>
Tomas
  • 333
  • 1
  • 15
0

Don't you have to overwrite the parent function foobar() too?

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

Foo::foobar();
Bar::foobar();
robx
  • 3,093
  • 2
  • 26
  • 29