Ok, one step better is the built in context switching action helper. This will make my code much easier to work with (I miss this from Solar

PHP Trickery

March 14th, 2009 by Ray in Computer Related, PHP/MySQL | Tags: | 2 Comments

While studying for my Zend certification, I came across a practice test question that asks what the primary difference is between a static method and a normal method. I figured this would be an easy question but I was almost tricked with false promises of language structure consistency*!

I was able to narrow my choices down to two answers: 1) static methods can’t be called from an instance and can only be called using the :: syntax, or 2) $this is not provided by static methods. I decided to play around with PHP a bit to find the answer and it turns out that the correct answer is number 2, which I knew but number 1 was throwing me off.

It turns out that you can call a static method from an instance, why you would want to I’m not sure.

Here’s an example:

class A {
    public static function foo() {
        return 'Hello';
    }
    public function bar() {
        return $this->foo();
    }
}
// normally I would just call:
echo A::foo();
// but this also works:
$instance = new A();
echo $instance->foo();
// and even this works!
$instance2 = new A();
echo $instance2->bar();

All of the examples above produce Hello.

Update: I will point out that this functionality is documented under Static Keyword in the PHP manual. Also, yesmarklapointe has a nice breakdown on what is returned under certain scenarios.

* PHP and Java have a lot of similarities when it comes to language structure but I guess most modern day languages do. I believe Java treats static methods the way you would expect–the only way to access a static method from outside of a Java class is by using the class name followed by the static method (e.g. A.foo()). To access foo() from within the same class you would just call foo().


2 Comments on “PHP Trickery”

  1. Jerome said at 1:52 pm on March 14th, 2009:

    Think if you have E_STRICT on that calling static as instance method might produce a E_STRICT failure, or warning… not sure.
    but yeah not sure why you would do that either :)

  2. Ray said at 2:17 pm on March 14th, 2009:

    The only time it throws a strict error at me is when I try to call a non-static method statically (e.g. A::bar()). I get the following message:

    PHP Strict Standards: Non-static method A::bar() should not be called statically…

    In the other cases above it appears to be OK.

Leave a Reply