0x6B6F77616C74
0x6B6F77616C74

Reputation: 2629

Initialising an array of objects

Program that tests the rand function is an example:

<?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);       
 ?>

Errors on the WAMP server:

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

What caused them and how to fix it? I suppose that the $integers is declared incorrectly.

Upvotes: 1

Views: 103

Answers (2)

fdomig
fdomig

Reputation: 4457

You should access members of an object with this syntax:

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

However you have to initialize your array first as well which means un-comment the initial line to

$integers = array();

As a matter of fact you are not using the better OOP style which would change your data structure like this:

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;
    }
}

You would then access the members like this:

// 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());
}

Upvotes: 3

Ruan Mendes
Ruan Mendes

Reputation: 92274

Why?

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

Should just be

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

There are no typed arrays in PHP

Upvotes: 3

Related Questions