0

I've got a very simple question but I don't get it. I've got a class with a few values looking like this:

class test_one{ private $value1, $value2; public function __construct($value1,$value2){ $this->$value1 = $value1; $this->$value2 = $value2; } } 

Now I want to create twenty objects of this class.

The Code in C# is looking like this:

ref = new test_one[20]; 

So my question is: how can I create 20 objects of the same class and save them in a reference so I can adress them by their Index?

3
  • 2
    You need to use loop Commented Oct 8, 2018 at 13:38
  • your assigning syntax is wrong Commented Oct 8, 2018 at 13:50
  • $this->value1 = $value1;$this->value2 = $value2; Commented Oct 8, 2018 at 13:51

2 Answers 2

1

You could do something along these lines:

<?php class test_one{ private $value1, $value2; public function __construct($value1,$value2){ $this->value1 = $value1; $this->value2 = $value2; } } for($i=1; $i<=20; $i++) { $var = "object" . $i; $$var = new test_one($value1 = $i, $value2 = $i*$i); } // show, say, object20 echo '<pre>'; print_r($object20); echo '</pre>'; 

output:

test_one Object ( [value1:test_one:private] => [value2:test_one:private] => [20] => 20 [400] => 400 ) 
Sign up to request clarification or add additional context in comments.

1 Comment

$value1 = $i, $value2 = $i*$i redundant assignments.
1

You need a loop, as already said in comments. Simple loop can be:

$i = 0; while ($i++ < 20) { $arr_of_objects[] = new test_one(); } 

Also, as already noticed in comments too, assigning values to class properties is done without $:

public function __construct($value1,$value2){ $this->value1 = $value1; $this->value2 = $value2; //----^ no $ here } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.