0

Learning OOP . . . How can I use the variable $bar that is passed to the instance method in Do_Stuff_1 and Do_Stuff_2?

class foo{
  public function __construct{} {
  }
  public static function instance( $bar ) {
  }
  public static function Do_Stuff_1() {
    // Make $bar available here.
  }
  public function Do_Stuff_2() {
    // Make $bar available here.
  }
}

2 Answers2

0

All you need to do is to store $bar in a static data member of the class in the instance method and after that you can use that throughout the class via static keyword like this

class foo {
    private static $bar;

    public function __construct() {
    }

    public static function instance( $bar ) {
        static::$bar = $bar;
    }

    public static function Do_Stuff_1() {
        // you can use this way static::$bar
        return static::$bar;
    }
    public function Do_Stuff_2() {
        // you can use this way static::$bar
    }
}

foo::instance(5);
echo foo::Do_Stuff_1(); // prints 5
Haridarshan
  • 1,898
  • 1
  • 23
  • 38
0

Store the input value in a static class property

class foo{
    private static $bar;

    public function __construct() {
    }

    public static function instance( $bar ) {
        self::$bar = $bar;
    }

    public static function Do_Stuff_1() {
        // Make $bar available here.
        echo 'Do_Stuff()_1 ' . self::$bar . PHP_EOL;
    }

    public function Do_Stuff_2() {
        // Make $bar available here.
        echo 'Do_Stuff()_2 ' . self::$bar . PHP_EOL;
    }
}
$f = new foo();
$f->instance('hip hip horray');
$f->Do_Stuff_1();
$f->instance('zipadie dodah');
$f->Do_Stuff_2();

RESULTS

Do_Stuff()_1 hip hip horray
Do_Stuff()_2 zipadie dodah
RiggsFolly
  • 93,638
  • 21
  • 103
  • 149