Visibility and Constructors
Private Property
A private property can only be changed from inside the class.
hidden state
Private state lets the class control how a value changes.
Private Property
private_property.php
Replay: real traced execution (multi-file project)
<?php
class ScoreBox
{
private int $score = 0;
public function add(int $points): int
{
$this->score = $this->score + $points;
return $this->score;
}
}
$points = 7;
$box = new ScoreBox();
$total = $box->add($points);
echo "points=" . $points . "\n";
echo "total=" . $total . "\n";
<?php
class ScoreBox
{
private int $score = 0;
public function add(int $points): int
{
$this->score = $this->score + $points;
return $this->score;
}
}
$points = 3;
$box = new ScoreBox();
$total = $box->add($points);
echo "points=" . $points . "\n";
echo "total=" . $total . "\n";
<?php
class ScoreBox
{
private int $score = 0;
public function add(int $points): int
{
$this->score = $this->score + $points;
return $this->score;
}
}
$points = 12;
$box = new ScoreBox();
$total = $box->add($points);
echo "points=" . $points . "\n";
echo "total=" . $total . "\n";
$points ← 7, $box ← ScoreBox
13$points→ 7 = 7; //@points=3, 1214$box→ ScoreBox = new ScoreBox();15$total = $boxScoreBox->add($points7);$this->score ← 7
6public function add(int $points7): int7{8 $this->score→ 7 = $this->score + $points7;9 return $this->score7;10}values this stepScoreBox$this$total ← 7
14$box = new ScoreBox();15$total→ 7 = $boxScoreBox->add($points7);1617echo "points=" . $points7 . "\n";18echo "total=" . $total7 . "\n";outputpoints=7 total=7
$points ← 3, $box ← ScoreBox
13$points→ 3 = 3;14$box→ ScoreBox = new ScoreBox();15$total = $boxScoreBox->add($points3);$this->score ← 3
6public function add(int $points3): int7{8 $this->score→ 3 = $this->score + $points3;9 return $this->score3;10}values this stepScoreBox$this$total ← 3
14$box = new ScoreBox();15$total→ 3 = $boxScoreBox->add($points3);1617echo "points=" . $points3 . "\n";18echo "total=" . $total3 . "\n";outputpoints=3 total=3
$points ← 12, $box ← ScoreBox
13$points→ 12 = 12;14$box→ ScoreBox = new ScoreBox();15$total = $boxScoreBox->add($points12);$this->score ← 12
6public function add(int $points12): int7{8 $this->score→ 12 = $this->score + $points12;9 return $this->score12;10}values this stepScoreBox$this$total ← 12
14$box = new ScoreBox();15$total→ 12 = $boxScoreBox->add($points12);1617echo "points=" . $points12 . "\n";18echo "total=" . $total12 . "\n";outputpoints=12 total=12