【问题标题】:php static variable initialization using the $this keyword使用 $this 关键字初始化 php 静态变量
【发布时间】:2019-07-19 21:26:29
【问题描述】:

我在一个类中有一个方法,我想在其中初始化一个静态变量。

1/ 当我初始化变量,然后使用 $this 关键字将其影响为其他值时,它可以工作。例如:

class Test {
   // ...
   function test($input_variable)
   {
      static $my_static_variable = null;
      if (!isset($my_static_variable))
        $my_static_variable = $this->someFunction($input_variable);
      // ... some further processing 
   }
}

2/ 但是,当我尝试使用$this 关键字直接初始化/构造变量时,出现语法错误:unexpected '$this' (T_VARIABLE):

class Test {
       // ...
       function test($input_variable)
       {
          static $my_static_variable = $this->someFunction($input_variable); // *** syntax error, unexpected '$this' (T_VARIABLE)
          // ... some further processing 
       }
}

1/ 是初始化静态变量的好方法吗? 为什么不允许 2/,因为它应该做与 1/ 完全相同的事情?

我正在使用 PHP 5.5.21 (cli)(构建时间:2016 年 7 月 22 日 08:31:09)。

谢谢

【问题讨论】:

  • 为什么需要在类方法中使用静态变量?请改用类属性:protected $my_static_variable;,然后使用 $this->my_static_variable = $this->someFunction();
  • @MagnusEriksson 我想使用一个静态变量,所以每次调用之间都会保留它的值。
  • 该值也将保留在类属性中。使用类属性的好处是您也可以从其他方法访问该变量,或者这不是您想要的?
  • @MagnusEriksson 是的,你是对的。我在下面写了一个解释。谢谢。

标签: php variables static initialization


【解决方案1】:

我想我有答案。在php documentation 中声明如下:

静态变量可以像上面的例子中看到的那样声明。从 PHP 5.6 你可以为这些变量赋值,这些变量是结果 表达式,但是你不能在这里使用任何函数,什么会导致 解析错误

所以我想这也适用于 PHP 5.5。

正如@MagnusEriksson 指出的那样,我也可以使用类属性。但是,我不希望在 test() 方法之外的其他地方访问我的变量。

顺便说一句,doc 中的静态属性以某种方式声明了相同的内容:

静态属性不能通过对象使用 箭头运算符 ->.

与任何其他 PHP 静态变量一样,静态属性只能是 在 PHP 5.6 之前使用文字或常量初始化;表达式 不允许。在 PHP 5.6 及更高版本中,适用与 const 相同的规则 表达式:一些有限的表达式是可能的,只要它们可以 在编译时进行评估。

【讨论】:

    【解决方案2】:

    无需实例化类即可访问静态变量和函数。您不能使用 $this 访问声明为静态的变量或函数。 您必须使用范围解析运算符:: 来访问声明为静态的变量和函数。

    对于变量:-

    class A
    {
        static $my_static = 'foo';
    
        public function staticValue() {
            return self::$my_static;// Try to use $this here insted of self:: you will get error
        }
    }
    
    class B extends A
    {
        public function fooStatic() {
            return parent::$my_static;
        }
    }
    

    使用以下方式访问变量:-

    print A::$my_static
    

    对于函数:-

    class A {
        public static function aStaticMethod() {
            // ...
        }
    }
    

    你可以如下调用函数:-

    A::aStaticMethod();
    

    【讨论】:

    • 在函数/方法中包含static $variable; 与静态类成员不同。
    【解决方案3】:

    您不能在静态变量上使用$this。您可以将self 与范围解析运算符 (::) 一起使用。

    示例如下:

    class Foo {
      public static $my_stat;
    
      static function init() {
        self::$my_stat= 'My val';
      }
    }
    

    【讨论】:

    • 在函数/方法中包含static $variable; 与静态类属性不同。
    猜你喜欢
    • 2011-08-22
    • 2010-12-22
    • 2015-12-09
    • 2021-10-28
    • 2017-05-13
    • 2010-12-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多