PHP4 Static Function Calls

I just noticed that PHP4 does not support any scope modifiers such as static and visibility modifiers like private and public on class members and methods. PHP5 supports all 3, and it took me a several minutes to figure out why my code wouldn’t run on one of the servers. It really creates funny situations. Consider the following example:

class Foo
    var $one = 1;
    function bar()
        echo "Helo World";
    function baz()
        echo $this->one;

We have and instance variable $one and two functions bar() and baz(). Tell me what happens when I do the following:

$foo = new Foo();
$foo->bar();    // prints Hello World
$foo->baz();    // prints 1
Foo::bar();    // prints Hello World
Foo::baz();    // throws an error

Note how I can call bar() both from the instance variable and statically without getting an error. As long as I don’t reference $this inside of a class function PHP4 will allow me to call it statically whenever I want. This is not necessarily wrong behavior, but since you have no way of enforcing a static nature of some functions things can get nasty. And by nasty I mean messy, and difficult to maintain.

Question is, do I really want to invest time into deploying PHP5 on that server and potentially run into a clusterfuck gauntlet when it inadvertently breaks some code dependencies? Meh… I think I will just have to deal without scope and visibility modifiers…

[tags]php, static, class, static functions, php4, php5[/tags]

This entry was posted in programming and tagged . Bookmark the permalink.

5 Responses to PHP4 Static Function Calls

  1. Gemma Peter UNITED KINGDOM Mozilla Firefox Debian GNU/Linux says:

    I ended up putting this line at the top of any instance methods to emulate the PHP5 differentiation between static and instance methods.

    if(is_null($this)) {die(‘instance method cannot be called statically’);}

    Reply  |  Quote
  2. Luke Maciak UNITED STATES Mozilla Firefox Ubuntu Linux Terminalist says:

    Nice! Or, maybe more elegantly:

    if(is_null($this)) throw new Exception('Instance method cannot be called statically.');

    This way gracefully handle errors caused by calling this method statically.

    I’m stealing the idea. :)

    Reply  |  Quote
  3. Luke Maciak UNITED STATES Mozilla Firefox Ubuntu Linux Terminalist says:

    Oh wait… PHP4 doesn’t have exceptions! Damn! :(


    Reply  |  Quote
  4. kakashi CHINA Mozilla Firefox Windows says:

    haha very good test

    Reply  |  Quote
  5. Cristian COLOMBIA Mozilla Firefox Gentoo Linux says:

    POO on PHP4 sucks… I rather prefer PHP5, it still sucks but not too much.

    Bye… thanks for the info.

    Reply  |  Quote

Leave a Reply

Your email address will not be published. Required fields are marked *