PHP 5 passing class Object as parameter, is it always a pointer or a copy or a clone?

Viewed 12889

I have a question about passing object as parameter. When we pass a variable, it creates a copy, but looks like object is always a reference pointer, is this correct? I have tested with the following example code:

class Base 
{
    private $var;
    function set ($var)
    {
        $this->var = $var;
    }

    function show ()
    {
        echo $this->var, '<br>';
    }
}

class Car
{
    private $obj;
    function __construct($obj)
    {
        $this->obj = $obj;
    }

    function set ($var)
    {
        $this->obj->set($var);
    }

    function show()
    {
        $this->obj->show();
    }
}

class Bus
{
    private $obj;
    function __construct($obj)
    {
        $this->obj = $obj;
    }

    function set ($var)
    {
        $this->obj->set($var);
    }

    function show()
    {
        $this->obj->show();
    }
}

And by running

$base = new Base();
$base->set('one');
$base->show();          // one

$bus = new Bus($base);
$bus->show();           // one

$car = new Car($base);
$car->set('two');
$car->show();           // two

$base->show();          // two

$bus->show();           // two

The display result is:

one
one
two
two
two

So changing the Base class's variable anywhere even it was passed as parameter into a function or another class will affect all of them, so does this mean it's always pointing to a same object as a pointer?

Thank you.

1 Answers
Related