0

I have two methods in a class, one of which is static. I want to access the non-static method from within the static method. Is that possible? I tried this:

class Foo {
   public function qux(){

   }
   public static function waldo(){
       self::qux(); // Non-static method Foo::qux() should not be called statically
   }
}

Is making qux a static method the only way to achieve this? What if the user doesn't want qux() to be a static method?

Tanmay
  • 3,009
  • 9
  • 53
  • 83
  • 2
    Possible duplicate of [calling non-static method in static method in Java](https://stackoverflow.com/questions/2042813/calling-non-static-method-in-static-method-in-java) – guyot Oct 01 '18 at 05:42

2 Answers2

1

This should work as you need:

class Foo {
   public function qux(){

   }

   public static function waldo(){
       $foo = new Foo();
       $foo->qux();
   }
}

There is no other way to call a dynamic method/function without creating the object itself first.

Of course, if you will use the object only one-time and call all methods or functions immediately, you could use something like this:

class Foo {
   public function qux(){

   }

   public static function waldo(){
       (new Foo())->qux();
   }
}
CodiMech25
  • 443
  • 3
  • 9
0
class Foo {

   public function qux(){

   }

   public static function waldo(){
       $obj = new Static();
       $obj->qux();

   }
}
Chayan
  • 604
  • 5
  • 12