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

1
  • 2
    PHP 5.3 introduced late static bindings. Looks like you might be out of luck with 5.2 Commented May 2, 2011 at 4:10

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

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();


?>

Comments

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();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.