Francois Francois - 3 years ago 141
PHP Question

Indirect access to a protected member of an object in PHP

I have a question about pointer in PHP.

In a A class i have :

protected $startDate;
public function getStartDate()
{
return $this->startDate;
}
public function setStartDate($startDate)
{
$this->startDate = $startDate;
}


I use it in my code like this :

$day = new \DateInterval('P1D');
$a->startDate->add($day);


Result : "Cannot access protected property" (as expected)




if I try :

$day = new \DateInterval('P1D');

print_r($a->getStartDate());

$date = $a->getStartDate();
$date->add($day);

print_r($a->getStartDate());
die();


Result :

DateTime Object
(
[date] => 2012-11-08 00:00:00
[timezone_type] => 3
[timezone] => Europe/Paris
)

DateTime Object
(
[date] => 2012-11-09 00:00:00
[timezone_type] => 3
[timezone] => Europe/Paris
)


I modified a protected value without the setter

I think that I modified the date value because it was returned as a pointer by the getter method.
I don't understand how I could modify a protected value without using a setter method.

Do you know why?

Thanks

Edit : Ok the member of my A class is a DateTime Object as I explained.
If I want it to be really protected, maybe I have to make a "timestamp" member and return a new DateTime of my timestamp (or clone the member).

Thanks again !

Answer Source

Objects are always passed by reference. To be more exact, there's only one object, and a variable just holds a reference to the object. By assigning the variable value to another variable, you copy the value, but that value is only a reference to the object.

In short: When working with objects in PHP, you're always passing around the object and all modifications to it will be visible to everyone who can see the object.

If you want to break that reference, clone the object.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download