Home  >  Article  >  Why does a String passed by reference not change its value?

Why does a String passed by reference not change its value?

WBOY
WBOYforward
2024-02-09 16:00:10797browse

In PHP, strings are immutable. This means that once a string is created, its value cannot be changed. When we pass a string by reference, we are actually passing a copy of the string rather than the original string itself. Therefore, any modifications to the copy will not affect the value of the original string. This is a protection mechanism designed by PHP to ensure the immutability of strings and the security of data. So no matter how we try to modify the value of a string by reference, we are actually creating a new string and assigning it to the reference variable, while the value of the original string remains unchanged.

Question content

Why does the following code only modify the value in the array t and does not change the value of the string s? I expected that the string would also change due to its object properties.

class A {
    private int i = 0;
    private String s = "";
    private int[] t = new int[1];

    void m() {
        B.m(i, s, t);
    }

    @Override
    public String toString() {
        return "i=" + i + ", s=" + s + ", t[0]=" + t[0];
    }
}

class B{
   public static void m(int i, String s, int[] t){
      i += 1;
      s += "1";
      t[0] += 1;
   }  
}

public class Zad {

   public static void main( String [ ] args ){
      A a = new A() ;
      System.out.println(a);
      a.m();
      System.out.println(a);
   } 
}

Workaround

This is what happens in your code: In java, when you pass a primitive type like int to a method, you pass is the value itself. Any modifications made to parameters within a method will not affect the original values ​​outside the method. This is called "passing by value". You probably already know this.

In the definition of class b, i, s and t are in the method m() local variables. This means that changes to these variables do not affect the original values ​​in the calling code.

When you call instance method a.m(); in the main method:

A a = new A();
System.out.println(a);  // Output: i=0, s=, t[0]=0
a.m();
System.out.println(a);  // Output: i=0, s=, t[0]=1

You will see that the value of t[0] has changed because arrays in java are objects and modifications to their elements are reflected outside the method. However, the values ​​of i and s remain unchanged because they are primitive types or immutable objects (such as string), and they are modified within the method. Any changes made are local and do not affect the original value.

The above is the detailed content of Why does a String passed by reference not change its value?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete