# Memory usage and refcount

- Thread: https://externals.io/message/51224
- Original archive: https://news-web.php.net/php.internals/51224
- Started by Patrick ALLAERT on 2011-01-05T17:30:15+00:00
- Messages: 2
- Reply by email to internals@lists.php.net
- More for agents: search with https://externals.io/search.md?q={query} · JSON API at https://externals.io/api · documentation at https://externals.io/llms.txt

---

## #51224 — Patrick ALLAERT — 2011-01-05T17:30:15+00:00

URL: https://externals.io/message/51224#51224

Hi,

While debugging some memory usage stuff I came across the fact that:

<?php
class foo {
    // $x as a static *class* var
    static $x = "foo";
    static function def() {
        return self::$x;
    }
}

$x1 = foo::def();
$x2 = foo::def();
$x3 = foo::def();
$x4 = foo::def();

xdebug_debug_zval('x4');
?>

will display a refcount of 5 while:

<?php
class foo {
    static function def() {
        // $x as a static *function* var
        static $x = "foo";
        return $x;
    }
}

$x1 = foo::def();
$x2 = foo::def();
$x3 = foo::def();
$x4 = foo::def();

xdebug_debug_zval('x4');
?>

will display a refcount of 1.

Can someone explain me why a real copy is made in the 2nd case?
Is this on purpose?

Regards,
-- 
Patrick Allaert
---
http://code.google.com/p/peclapm/ - Alternative PHP Monitor

---

## #51226 — johannes@php.net — 2011-01-05T18:15:34+00:00

URL: https://externals.io/message/51224#51226 · In reply to: #51224

> <?php
> class foo {
>     static function def() {
>         // $x as a static *function* var
>         static $x = "foo";
>         return $x;

$x is a reference to the static variable. It has to since assignment to
$x, which is a local variable, should change the static variable. This
is returned using copy semantis so we can't do copy on write.

Whereas with 

> class foo {
>     // $x as a static *class* var
>     static $x = "foo";
>     static function def() {
>         return self::$x;
>     }
> }

you are explicitly referencing the static class property. CoW can work
properly.

johannes
