问题
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.
回答1:
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:
$arr[0] = & new MyClass(1,2);
Gives you a strict standards error. You can not assign a reference/alias with the new keyword. Probably this way of writing is influenced by PHP 4 code, but this has changed since PHP 5 which introduced the object store.
回答2:
The method content will be stored only once in memory. Every PHP object (of the said class) will have a reference to the method.
So to conclude: you don't have to care about the memory size of your methods if you plan to have a lot of objects. Just care about the memory size of the objects attributes.
This is, for example, different than in Javascript, where each class-defined method is contained in each instance. However, if you define a method in its prototype, then the method is shared by all class instances (lighter in memory of course). See this link: http://webdevelopersjournal.com/articles/jsintro3/js_begin3.html.
来源:https://stackoverflow.com/questions/7828515/in-php-are-objects-methods-code-duplicated-or-shared-between-instances