【问题标题】:PHP How to use a variable passed to a method throughout the entire class? [duplicate]PHP如何在整个类中使用传递给方法的变量? [复制]
【发布时间】:2021-09-03 10:03:09
【问题描述】:

学习面向对象编程。 . .如何使用传递给 Do_Stuff_1 和 Do_Stuff_2 中的实例方法的变量 $bar?

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.
  }
}

【问题讨论】:

    标签: php class oop


    【解决方案1】:

    您需要做的就是将$bar 存储在instance 方法中类的static 数据成员中,然后您可以通过static 关键字在整个类中使用它

    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
    

    【讨论】:

      【解决方案2】:

      将输入值存储在静态类属性中

      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();
      

      结果

      Do_Stuff()_1 hip hip horray
      Do_Stuff()_2 zipadie dodah
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-06-28
        • 2013-05-31
        • 2016-01-01
        • 1970-01-01
        • 2012-09-15
        • 2012-06-03
        • 1970-01-01
        相关资源
        最近更新 更多