-1

I was reading PHP manual link for OOPs concept and came across few examples which I was not able to understand.

a) Can someone please explain whether the objects are getting passed by value or reference?

b) What is reference, pointer and identifier and what is difference between them?

Example 1:

class A {
    public $foo = 1;
}  

class B {
    public function foo(A $bar)
    {
        $bar->foo = 42;
    }

    public function bar(A $bar)
    {
        $bar = new A;
    }
}

$f = new A;
$g = new B;
echo $f->foo . "n";

$g->foo($f);
echo $f->foo . "n";

$g->bar($f);
echo $f->foo . "n";

Expected Output:

1
42
1

Returned Output:

1
42
42

Example 2:

class A
{
    public $v = 1;
}

function change($obj)
{
    $obj->v = 2;
}

function makezero($obj)
{
    $obj = 0;
}

$a = new A();

change($a);    
print_r($a); 
//Expected: A Object ( [v] => 2 ) 
//Returned: A Object ( [v] => 2 )  

makezero($a);    
print_r($a);
//Expected: 0 
//Returned: A Object ( [v] => 2 ) 

Reference 1

Reference 2

D555
  • 1,704
  • 6
  • 26
  • 48

1 Answers1

0

According to the php docs:

By default, function arguments are passed by value (so that if the value of the argument within the function is changed, it does not get changed outside of the function). To allow a function to modify its arguments, they must be passed by reference.

To have an argument to a function always passed by reference, prepend an ampersand (&) to the argument name in the function definition.

In B::foo you do not change the variable, but the property of the variable's object. That's why you get 42

In B::bar you change the variable directly. It is changed to a new instance of A. Inside B::bar the value of $bar->foo === 1.

Pointers: Pointers are generated, whenever an object is created and assigned to a variable. This variable stores a memory address to access the object.

References: References are created with an ampersand (&).

//from your link posted
$a = new Foo; // $a is a pointer pointing to Foo object 0
$b = $a; // $b is a pointer pointing to Foo object 0, however, $b is a copy of $a
$c = &$a; // $c and $a are now references of a pointer pointing to Foo object 0
schildi
  • 136
  • 7