3

Possible Duplicate:
What exactly is late-static binding in PHP?

In this example, PHP will print "NO" rather than "YES", opposite of what I expected.

If I remove static on function c(), replace self:: with $this-> and do $e = new B; $e->c();, things will work.

Does this mean that instantiation is required to make functions in parent classes call overridden functions in inherited classes?

(Side question: Is this a PHP quirk, or does this logic also apply for most other programming languages? If so, what is the rationale behind it?)

class A {
  static function c() {
    self::d();
  }
  static function d() {
    echo "NO :(\n";
  }
}

class B extends A {
  static function d() {
    echo "YES :)\n";
  }
}

B::c();
Community
  • 1
  • 1
forthrin
  • 2,709
  • 3
  • 28
  • 50

1 Answers1

7

You need to use static keyword instead of self or $this.

<?php

class A {
    static function c() {
        static::d();
    }
    static function d() {
        echo "NO :(\n";
    }
}

class B extends A {
     static function d() {
         echo "YES :)\n";
     }
}

B::c();

// YES :)

This behavior is called Late Static Bindings.

Boris Guéry
  • 47,316
  • 8
  • 52
  • 87