PHP [OOP]:继承的内存分配

发布于 2024-08-15 07:06:02 字数 429 浏览 6 评论 0原文

请看下面的代码:

class A {
    public x = 5;
    public y = 6;
    public z = 7;
}

class B extends A {
    public m = 1;
    public n = 2;
}

$a = new A();
$b = new B()

从上面的代码中让$a分配x内存量和$b正在分配 y 内存量;

现在我的问题是下面哪一个是正确

x> y

x <是的

Please see the code bellow:

class A {
    public x = 5;
    public y = 6;
    public z = 7;
}

class B extends A {
    public m = 1;
    public n = 2;
}

$a = new A();
$b = new B()

From the above code let $a is allocating x amount of memory and $b is allocating y amount of memory;

Now my question is which one is correct from bellow?

x > y

x < y

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

山川志 2024-08-22 07:06:02

这些是我的数字:

Starting allocation 62480
Allocated memory for new A() 328
Allocated memory for new B() 496

因此 x < y

这两个类定义是等效的,

class B extends A {
    public $m = 1;
    public $n = 2;
}

class C {
    public $x = 5;
    public $y = 6;
    public $z = 7;
    public $m = 1;
    public $n = 2;
}

这意味着如果您将 B 的定义更改为 C 的定义,那么使用 new B() 或 new C() 的内存使用量将完全相同。

要自己运行它,请使用此代码(作为示例)

$start = memory_get_usage();
echo "Starting allocation $start\n";
$a = new A();
$diff = memory_get_usage() - $start;
echo "Allocated memory for new A() $diff\n";
$b = new B();
$diff = memory_get_usage() - $start - $diff;
echo "Allocated memory for new B() $diff\n";

These are my numbers:

Starting allocation 62480
Allocated memory for new A() 328
Allocated memory for new B() 496

Thus x < y

These two class definitions are equivalent

class B extends A {
    public $m = 1;
    public $n = 2;
}

class C {
    public $x = 5;
    public $y = 6;
    public $z = 7;
    public $m = 1;
    public $n = 2;
}

Meaning that were you to change the definition of B into that of C then the memory usage would be the exact same for using new B() or new C().

To run it yourself use this code (as an example)

$start = memory_get_usage();
echo "Starting allocation $start\n";
$a = new A();
$diff = memory_get_usage() - $start;
echo "Allocated memory for new A() $diff\n";
$b = new B();
$diff = memory_get_usage() - $start - $diff;
echo "Allocated memory for new B() $diff\n";
埖埖迣鎅 2024-08-22 07:06:02

您可以使用 memory_get_usage 函数来调查此问题。

You can investigate this by using the memory_get_usage function.

说好的呢 2024-08-22 07:06:02

它应该是公共$x、$y、$z。

而 $b 占用的内存较多,因为它里面有 A 的实例。

It should be public $x, $y, $z.

And $b takes up more memory because it has an instance of A inside.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文