在PHP中,是对象方法code复制或实例之间共享? [英] In PHP, are objects methods code duplicated or shared between instances?

查看:70
本文介绍了在PHP中,是对象方法code复制或实例之间共享?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在PHP中,如果使物体的阵列,是在阵列中复制的对象的每个实例,或者仅一次的对象的方法(不是数据成员)?我会认为内存的原因,后者是真实的;我只是想用计算器社区,这是真正的确认。

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.

例如,假设我有一个MyClass类有两个方法,即。

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() {  }
}

显然,在现实中方法1()和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);

因此​​PHP是存储三组数据成员在内存中,每个三个对象实例。我的问题是,PHP也储存方法一()和method2()(和构造函数)的副本,3倍,为每个$ 3个元素的改编?我试图决定〜200对象数组是否是因为有存储每个方法的200份记忆太内存密集型。

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.

感谢您的时间。

推荐答案

根据定义(这是的的code)中,功能只存在一次。这就是为什么你产生code(而不是数据)。

By definition (and that is your code), a function only exists once. That's why you produce code (and not data).

不过,就可以使用您的code,产生大量的数据。但是,这是另一个故事。)

However, you can then use your code to produce a lot of data. But that's another story ;).

所以,除非你不跨越不必要的重复对象code,你的功能(S)将只存在一次。独立多少创建code的的实例的。只有关联到code(类成员)中的数据是重复的。

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.

听起来很公平吗?

BTW:

$arr[0] = & new MyClass(1,2);

为您提供了一个严格的标准错误。您不能分配与关键字参考/别名。也许写的这种方式是由PHP 4 code的影响,但由于PHP 5里面介绍对象存储这种情况已经改变。

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.

这篇关于在PHP中,是对象方法code复制或实例之间共享?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆