Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do all references to a string literal refer to same instance?

Tags:

string

php

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

like image 398
SoWhat Avatar asked Sep 10 '13 08:09

SoWhat


People also ask

How does string literal work?

A "string literal" is a sequence of characters from the source character set enclosed in double quotation marks (" "). String literals are used to represent a sequence of characters which, taken together, form a null-terminated string. You must always prefix wide-string literals with the letter L.

What is difference between literal and string literal?

Definition. String literal in Java is a set of characters that is created by enclosing them inside a pair of double quotes. In contrast, String Object is a Java is a set of characters that is created using the new() operator. Thus, this explains the main difference between string literal and string object.

Which is an example of a string literal?

A string literal is a sequence of zero or more characters enclosed within single quotation marks. The following are examples of string literals: 'Hello, world!' 'He said, "Take it or leave it."'

How is a string literal stored in the memory?

The characters of a literal string are stored in order at contiguous memory locations. An escape sequence (such as \\ or \") within a string literal counts as a single character. A null character (represented by the \0 escape sequence) is automatically appended to, and marks the end of, each string literal.


1 Answers

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.

like image 155
LostAvatar Avatar answered Oct 17 '22 04:10

LostAvatar