Sep | OCT | MAR
| 18 |
2005 | 2006 | 2007

2 captures 18 Oct 06 - 13 Mar 07 |

Close Help

edit

## Late static binding

Wed, 19 Jul 2006 17:23:00 GMT

Update: This has been discussed and will be uh, sort of fixed, in PHP6. You’ll be able to use static::my_method() to get the real reference to self in class methods. Not optimal, but still a solution I guess.

As colder on ##php (freenode) told me today, class methods in PHP don’t have what they call late static binding. What’s that? It means that this code:

    class Foo
    {
      public static function my_method()
      {
        echo "I'm a " . get_class() . "!\n";
      }
    }

    class Bar extends Foo
    {}

    Bar::my_method();

outputs “I’m a Foo!”, instead of “I’m a Bar!”. That’s not fun.

Using `__CLASS__` in place of `get_class()` makes zero difference. You end up with proxy methods in each subclass of Foo that pass in the real name of the calling class, which sucks.

    class Bar extends Foo
    {
      public static function my_method()
      {
        return parent::my_method( get_class() );
      }
    }

I was told that they had a discussion about this on the internal PHP list, so at least they’re thinking about this stuff. Too bad PHP5 doesn’t have it. I guess I should just be glad I won’t be maintaining this code.

The resident PHP coder said “just make your code simpler”, which is what I was trying to do by removing duplication. Too bad that plan sort of backfired. I guess odd things like this are where PHP starts to show that OO was tacked on as an after-thought.

Posted in php, coding | Tags coding, php | 2 comments | no trackbacks

#### Comments

Leave a response

1. nuke edit
   Jim Roepcke said 25 days later:

   That’s the worst of both worlds.

   In Objective-C, that would work properly. In Java, it wouldn’t work at all because static methods (Java doesn’t have class methods) aren’t inherited by subclasses, so at least if you called the method on the superclass the result would be consistent…. but this, this crap (as PHP always is), well, it isn’t consistent with anything. Doesn’t get any worse. But, I’m hardly surprised.

2. nuke edit
   Sami said 34 days later:

   Interesting about Java, I didn’t know static methods weren’t inherited.

   I have to say that I don’t know if I can work another job using PHP and keep my sanity. :)

#### Trackbacks

Use the following link to trackback from your own site:
http://sami.samhuri.net/articles/trackback/430

RSS feed for this post trackback uri

Your name | (leave url/email »)
Your blog |
Your email |
Your message |
Preview comment

# sjs

##