In PHP, if you make an array of objects, are the object methods (not data members) copied for each instance of the object in the array, or only once? I would assume that for memory reasons, the latter is true; I just wanted to confirm with the StackOverflow community that this is true.
For example, suppose I have a class MyClass with a couple of methods, i.e.
class MyClass {
public $data1;
private $data2;
public function MyClass($d1, $d2) {
$this->data1=$d1; $this->data2=$d2;
}
public function method1() { }
public function method2() { }
}
Obviously in reality method1() and method2() are not empty functions.
Now suppose I create an array of these objects:
$arr = array();
$arr[0] = & new MyClass(1,2);
$arr[1] = & new MyClass(3,4);
$arr[2] = & new MyClass(5,6);
Thus PHP is storing three sets of data members in memory, for each of the three object instances. My question is, does PHP also store copies of method1() and method2() (and the constructor), 3 times, for each of the 3 elements of $arr? I’m trying to decide whether an array of ~200 objects would be too memory-intensive, because of having to store 200 copies of each method in memory.
Thanks for your time.
By definition (and that is your code), a function only exists once. That’s why you produce code (and not data).
However, you can then use your code to produce a lot of data. But that’s another story ;).
So unless you do not needlessly duplicate code across objects, your function(s) will only exist once. Independent how many instances of the code you create. Only the data associated to the code (the class members) are duplicated.
Sounds fair?
BTW:
Gives you a strict standards error. You can not assign a reference/alias with the
newkeyword. Probably this way of writing is influenced by PHP 4 code, but this has changed since PHP 5 which introduced the object store.