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

2 captures 18 Oct 06 - 13 Mar 07 |

Close Help

edit

## Class method? Instance method? It doesn't matter to PHP

Fri, 21 Jul 2006 14:56:00 GMT

Update: This has been discussed for PHP6. A little late, but I guess better than never.

I made a mistake while I was coding, for shame! Anyway this particular mistake was that I invoked a class method on the wrong class. The funny part was that this method was an instance method in the class which I typed by mistake. In the error log I saw something like “Invalid use of $this in class function.”

I knew for a fact I hadn’t used $this in a class method, so it was kind of a confusing error. I went to the file in question and found out that it was calling an instance method as a class method. Now that is some crazy shit.

I would fully expect the PHP parser to give me an error like “No class method [foo] in class [blah]”, rather than try and execute it as a class method. The syntax is completely different; you use :: to call a class method and -> to call an instance method. And you use the name of a class when you call a class method.

This code:

    class Foo {
      public static function static_fun()
      {
        return "This is a class method!\n";
      }

      public function not_static()
      {
        return "This is an instance method!\n";
      }
    }

    echo '<pre>';
    echo "From Foo:\n";
    echo Foo::static_fun();
    echo Foo::not_static();
    echo "\n";

    echo "From \$foo = new Foo():\n";
    $foo = new Foo();
    echo $foo->static_fun();
    echo $foo->not_static();
    echo '</pre>';

Produces:

    From Foo:
    This is a class method!
    This is an instance method!

    From $foo = new Foo():
    This is a class method!
    This is an instance method!

What the fuck?! http://www.php.net/manual/en/language.oop5.static.php is lying to everyone.

Posted in php, coding | no comments | no trackbacks

#### Comments

Leave a response

#### Trackbacks

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

RSS feed for this post trackback uri

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

# sjs

##