2

Since when PHP allows to call static function like a dynamic function?

I am using php 5.3.2

class weird{

    public static function iamstatic($calledFrom){
            echo "I am  a static function called with  a $calledFrom operator\n";
    }

    public function test(){
            self::iamstatic("static");
            $this->iamstatic("dynamic");
    }

 }

$c = new weird();
$c->test();

weird::iamstatic("Static outside class");
$c->iamstatic("Dynamic outside class");

This outputs :

I am  a static function called with  a static operator
I am  a static function called with  a dynamic operator
I am  a static function called with  a Static outside class operator
I am  a static function called with  a Dynamic outside class operator
1
  • Better to use non static definition for that. Commented Jul 17, 2014 at 5:38

2 Answers 2

4

It was always possible for php5.0 and above.

http://3v4l.org/14PYp#v500

Also, it's mentioned in documentation (static)

Declaring class properties or methods as static makes them accessible without needing an instantiation of the class. A property declared as static cannot be accessed with an instantiated class object (though a static method can).

And this not a bug (static methods assigned to instances)

Sign up to request clarification or add additional context in comments.

5 Comments

Good point, though I think this (no bug) is really infamous... For example, I was reading my code, thinking that this method definition was dynamic. I was really surprised to realize it was a static method. I think this is bad, cause it might make the developer believe that the method is declared as dynamic, and though can't be accessed from outside the class without being instanciated.
@Cooluhuru, i do not think so because i am using it (helper methods that not affect to object state).
It Works for you cause they are protected.
@Cooluhuru, sorry. Not protected only (after some re search).
@Cooluhuru , have you got your answer?
0

I wasn't aware this was possible, although it probably doesn't matter. Your static method won't let you reference $this, so you won't get very far using it in a non static context. If you don't need to refer to $this, then it won't matter either way, which is what your code is proving.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.