Are data types in php categorized into reference type and value type? Like C#

1.5k Views Asked by At

In c#,data type is divided into reference type and value type.

Then in php,data type is still divided as c#?

I find a interesting thing.

array is a reference type in most language.

for example, in c#:

    int[] a ={1,4,5};
    int[] b = a;
    a[1] = 10;
    print(a);
    print(b)

both a and b are [1,10,5]

but in php,suppose there is below code:

<?php
$a=array(1,4,5);
$b=$a;
$a[1]=10;
print_r($a);
print_r($b);
?> 

in the end, the $a is (1,10,5) and the $b is (1,4,5). It seems the array in php is value type.

So who can answer my question: Are data types in php categorized into reference type and value type?

1

There are 1 best solutions below

2
On

Yes, essentialy objects are stated to be reference type while everything else is value type. However, the former is not completely true and might be better described as 'pointer type'.

To give an example:

$a = new stdClass(); # <-- Obj1
$a->foo = 'foo';
$b = $a;
$b->foo = 'bar';
echo $b->foo; # outputs 'bar'
echo $a->foo; # outputs 'bar'

As you can see, it would seem that $a is being passed by reference; it is, however, actually a copy of the identifier of that object that is being passed. As such, updating a property will affect the original, but updating the value of the variable will not. This contrast with a true PHP reference as follows:

$c =& $a;
$c = new stdClass(); # <-- Obj2
$c->foo = 'foo';
echo $b->foo; # outputs 'bar'
echo $a->foo; # outputs 'foo'

Here we create a "true reference" of $a as/in $c. This holds that any alteration to $a will result in $c being altered and vice versa. As such, when we update the value of $c, $a is also updated and points to Obj2; meanwhile $b is left unaffected by the value being altered and still points to Obj1.