2016-02-16 05:10
浏览 29

PHP OOP数组在方法中重复

Very new to OOP so please bear with me. I have a method that checks characteristics of a persons array and has a counter to keep track of things. The persons array starts off as serialized data, which I'm converting to an array with the unzerialize() function. When I do var_dump($this->people) in the constructor, I get the correct values. When I do the same in any of the other methods in the class, the array is duplicated a number of times and my counter produces incorrect values.

Also doing echo gettype($this->people) in the constructor results in array as expected, but in the other methods results in arrayarrayarrayarray....

What could be causing this duplication? And how do I solve it?

* EDIT *

Sorry for the confusion. I did not know where the problem was so it was difficult for me to explain properly.

The problem is not with my class definition, but how I am using the object. I have reworked the code to illustrate. I thought that once the object was instantiated, the values produced by it would be set, however it turns out that each time I call the get_results() method, $this->num is incremented and the value is persisted.

So my question is, how do I run the get_results() method once, and access the results[] array without changing the values? I was hoping I could do something like if($nums['results']['num'] == 1) but that results in a fatal error.

class DoStuff
    private $num;
    public $results;

    public function __construct($val)
        $this->num = $val;
        $this->results = [];

    private function compute_num()
        $this->results['num'] = $this->num;
        return $this->results;

    public function get_results()
        $this->results = $this->compute_num();
        return $this->results;

$nums = new DoStuff(0);

if($nums->get_results()['num'] == 1)
    printf('<p>(if) Num is: %d</p>', $nums->get_results()['num']);
    printf('<p>(else) Num is: %d</p>', $nums->get_results()['num']);

// Prints (else) Num is: 3
  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

1条回答 默认 最新

相关推荐 更多相似问题