6

One of my colleagues made a post that said something like this:

In PHP, if you have two variables referring to the same value, they are the same instance.

$a="Mary";
$b="Mary";
$c="lamb"

He implies that $a and $b refer to the same instance(memory space). I am having trouble beleiving this. I know that this is somewhat true in java, but I don't think its so for php, since in php strings aren't actually immutable by principle, it would not make sense to have one instance

Further,he said, if we do unset($a) it only removes the reference of $a not the actual value. This is ofcourse true, but proves nothing

I also tried the following code and printed both $a and $b. If they were sharing the same instance, the value of $b would have changed too.

$a[2]=3;
echo "<br/>\$a: $a<br/>"; //He3lo
echo "<br/>\$b: $b<br/>";//Hello

I would love to check the memory space of the variables, but I don't think php allows to do that. Can somebody clarify if this is true

LostAvatar
  • 795
  • 7
  • 20
SoWhat
  • 5,564
  • 2
  • 28
  • 59
  • 1
    Simple test: create a long string literal and measure the memory consumption. Then do the same with two identical long string literals. Even if PHP optimizes the memory storage internally, it does not in any way behave as if it did in user land code. – deceze Sep 10 '13 at 08:21
  • http://stackoverflow.com/questions/5153528/how-check-memory-location-of-variable-in-php – str Sep 10 '13 at 08:22
  • 2
    Measure it, test it. That's the best way. Answer, however, is _not_ - since PHP using copy-on-write memory management method. – Alma Do Sep 10 '13 at 08:23
  • 1
    *I also tried the following code and printed both `$a` and `$b`. If they were sharing the same instance, the value of `$b` would have changed too.* No, because PHP does copy on write. If you try `$a = "Mary"; $b = $a;` you will get the same result even though this time they do share the same instance. [Here's an example](http://ideone.com/jzuQHd). – Jon Sep 10 '13 at 08:58
  • You can use `debug_zval_dump` function too! – undone Sep 10 '13 at 09:27
  • Okay, I tried the long string thing in php(5.3) and well, it seems that PHP does create a different instance per string. Not sure about php 5.4 – SoWhat Sep 10 '13 at 10:29

1 Answers1

2

You are referring to a concept called String interning. It seems that it is implemented in the Zend Engine since Version 5.4: "Our implementation makes the strings which are known at compile-time interned." Source.

LostAvatar
  • 795
  • 7
  • 20