Php – how to call non static methods from static methods

This is interview’s burning question for fresher and experienced professional guys. Because, It contains all logic of oops concepts .Before know the answer of this question , you must know the about static function and class.

first , we are going to define the static methods :-

as we know the static methods is nothing , but it access without creating  the objects of the class. It means , this methods only access by scope resolution and $this is not available in static methods. This is the very important things.

 

Ex:-

Class Do {
  static public function test() {
      return something;
  }
}

use :-

echo Do::test();


  This is above definition,  how to defines static methods. I think , Now you have little bit idea about this.

Now we are going to explain , how non- static methods calling from static methods:-

 

Suppose as general , if we call simple methods from methods then we can use simple $this, but in this scenario , $this is not allowed in static methods, so we can use in different ways like :-

class Alexa {

    public function fun1() {
        echo 'non-static';   
    }

    public static function fun2() {
        echo (new self)->fun1();
    }
}

 

explanation:-  

Alexa is class name . It having one non static methods fun1() and second function name is fun2() that is static methods.

Now, as we told earlier that , we can not use $this in static methods , then how to call non static methods in static methods.

We will create by new self, That is represents of current class and then , call the function by new self operators.

 

This is above syntax ,  it is well defined about , How to call non static methods from static methods. I think, it is very clear for you .

 

 

Thank you from our team at alexawork.com

 

 

 

You may also like...

1 Response

  1. Good day! Would you mind if I share your blog with my
    zynga group? There’s a lot of people that I think would really enjoy your content.
    Please let me know. Thanks

Leave a Reply

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