2012-07-17 92 views
1

程序,测试RAND函数是一个例子:WAMP服务器上正在初始化对象的数组

<?php 
     class number { 
      function number() { 
       $occurences=0; 
      } 
      public $occurences; 
      public $value; 
     } 
     $draws = 5000; 
     $numOfInts = 10; 
     //$integers = array(); 
     $integers [] = new number(); 
     //initialising loop 
     for($i=0;$i<=$numOfInts;$i++) 
      $integers[$i]->$value = $i; //debugger points here 

     for($i=0;$i<$draws;$i++) { 
      $integers[rand(0,numOfInts)]->$occurences++;    
     } 
     foreach($integers as $int) 
      printf("%5d %5d <br/>",$int->$value,$int->$occurences);  
?> 

错误:

Undefined variable: value in C:\path\index.php on line 31

Fatal error: Cannot access empty property in C:\path\index.php on line 31

是什么原因造成,以及如何解决它?我想,$整数是不正确的声明。

+0

这不是OOP。 – 2012-07-17 19:40:57

回答

3

你应该访问对象的成员语法:

$integers[$i]->value 
$integers[$i]->occurences; 

但是你必须首先初始化您的阵列,这意味着取消注释最初的行到

$integers = array(); 

由于实际上没有使用更好的OOP风格,将改变你的数据结构是这样的:

class Number { 
    private $value; 
    private $occurences = 0; 
    public function __construct($value = 0) { 
     $this->value = $value; 
    } 
    public function getValue() { 
     return $this->number; 
    } 
    public function addOccurence() { 
     $this->occurences++; 
    } 
    public function getOccurences() { 
     return $this->occurences; 
    } 
} 

你会再访问成员如下:

// init part 
$integers = array(); 
for($i = 0; $i < $numOfInts; $i++) { 
    $integers[] = new Number($i); 
} 

// draws part 
for($i=0; $i < $draws; $i++) { 
    $integers[rand(0,$numOfInts-1)]->addOccurence();    
} 

// print part 
foreach($integers as $number) { 
    printf("%5d %5d<br />", $number->getValue(), $number->getOccurences()); 
} 
3

为什么?

//$integers = array(); 
$integers [] = new number(); 

应该只是

$integers = array(); 
for($i=0;$i<=$numOfInts;$i++) { 
    $integers[$i] = new number(); 
} 

PHP中

没有类型数组
+0

这是问题的一部分,下半年的问题是@fdomig指出的。 – tigrang 2012-07-17 19:44:28

+0

@fdomig指出的是代码不是面向对象,这不是问题的一部分,也不是为什么它不起作用。 – 2012-07-17 19:50:31

+0

这是不对的@JuanMendes,它不工作,因为'$ number - > $ value'部分。 – fdomig 2012-07-17 19:51:17