Reputation: 43
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 !
Upvotes: 3
Views: 172
Reputation: 332
With $date = $a->getStartDate();
you create a new variable.
With $date->add($day);
you change that new variable's value, not the origin.
Upvotes: 0
Reputation: 1264
Try this:
protected $startDate;
public function getStartDate()
{
return clone $this->startDate;
}
public function setStartDate($startDate)
{
$this->startDate = $startDate;
}
Upvotes: 0
Reputation: 522015
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.
Upvotes: 2