Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/variables/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用$this关键字初始化php静态变量_Php_Variables_Static_Initialization - Fatal编程技术网

使用$this关键字初始化php静态变量

使用$this关键字初始化php静态变量,php,variables,static,initialization,Php,Variables,Static,Initialization,我在一个类中有一个方法,我想在其中初始化一个静态变量 1/当我初始化变量,然后使用$this关键字将其影响为其他值时,它会工作。例如: class Test { // ... function test($input_variable) { static $my_static_variable = null; if (!isset($my_static_variable)) $my_static_variable = $this->

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

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
关键字直接初始化/构造变量时,出现语法错误:
意外的'$this'(T_变量)

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

我使用的是PHP5.5.21(cli)(构建时间:2016年7月22日08:31:09)


谢谢

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

以下是一个例子:

class Foo {
  public static $my_stat;

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

静态变量和函数可以在不实例化类的情况下访问。不能使用$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();

我想我有答案了。合同中规定如下:

静态变量可以在上面的示例中声明。从…起 PHP5.6可以为这些变量赋值,这些变量就是结果 对于表达式,但是您不能在这里使用任何函数,什么会导致 分析错误

所以我想这也适用于PHP5.5

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

顺便说一句,在下面的例子中,对于静态属性也有同样的说法:

无法通过使用 箭头运算符->。

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


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