duanhuau567787
2017-09-09 07:16
浏览 82
已采纳

一个用户请求期间php中的静态变量

I try to use a variable in each instance for a class.

My example class:

class test {
    private static $gvalue;

    function setValue($value)
    {
        $this->gvalue = $value;
    }

    function getValue()
    {
        return $this->gvalue;
    }

}

Now I create to instances of this class "test" and print out some values.

$obj = new test();
$obj2 = new test();
echo "1: ";
echo $obj->getValue();
echo " / ";
echo $obj2->getValue();
$obj->setValue("green");
echo "<BR>2: ";
echo $obj->getValue();
echo "/";
echo $obj2->getValue();

My expectation was to get the following output:

1: / 2: green/green

But the result is:

1: / 2: green/

Did I understand something wrong? Or ist that not possible in PHP? Goal at the end. I would like to set some variables/arrays during the creation of an instance (__construc) and us that for every instance during the code (per user request).

图片转代码服务由CSDN问答提供 功能建议

我尝试在每个实例中为一个类使用一个变量。

我的示例类:

  class test {
 private static $ gvalue; 
 
 function setValue($ value)
 {
 $ this-&gt; gvalue =  $ value; 
} 
 
函数getValue()
 {
返回$ this-&gt; gvalue; 
} 
 
} 
   
 
 <  p>现在我创建这个类的实例“test”并打印出一些值。 
 
 
  $ obj = new test(); 
 $ obj2 = new test()  ; 
echo“1:”; 
echo $ obj-&gt; getValue(); 
echo“/”; 
echo $ obj2-&gt; getValue(); 
 $ obj-&gt; setValue(“green”);  
echo“&lt; BR&gt; 2:”; 
echo $ obj-&gt; getValue(); 
echo“/”; 
echo $ obj2-&gt; getValue(); 
   \  n 
 

我的期望是得到以下输出:

1:/ 2:绿色/绿色

但结果是 :

1:/ 2:green /

我是否理解错误? 或者这在PHP中是不可能的? 最后的目标。 我想在创建实例(__construc)期间设置一些变量/数组,并在代码期间(每个用户请求)为每个实例设置一些变量/数组。

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • dsovc00684 2017-09-09 07:25
    已采纳

    You have to change how you access the static property in your method implementation:

    <?php
    
    class Test {
      private static $gvalue;
    
      function setValue($value) {
        self::$gvalue = $value;
      }
    
      function getValue() {
        return self::$gvalue;
      }
    }
    
    $obj1 = new Test();
    $obj2 = new Test();
    echo sprintf("1: %s/%s
    ", $obj1->getValue(), $obj2->getValue());
    
    $obj1->setValue("green");
    echo sprintf("2: %s/%s
    ", $obj1->getValue(), $obj2->getValue());
    

    The output of that is:

    1: /
    2: green/green
    
    已采纳该答案
    评论
    解决 无用
    打赏 举报
  • douti8321 2017-09-09 07:22

    You only set $gvalue for $obj:

    $obj->setValue("green");
    

    When you echo $obj2->getValue(); the value of $gvalue is still nothing, because you didn't set it for $obj2.

    $obj and $obj2 are both different instances of the same class. They have the same characteristics etc. but they can hold different values. Thus the output that you got:

    1: / 2: green/
    

    is the correct output.

    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题