duanhuau567787
duanhuau567787
2017-09-09 07:16

一个用户请求期间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).

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

2条回答

  • dsovc00684 dsovc00684 4年前

    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 douti8321 4年前

    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.

    点赞 评论 复制链接分享