Classes and Objects
Object State
An object can update its own state across method calls.
Object State
object_state.php
<?php
class Counter
{
public int $value = 0;
public function add(int $amount): int
{
$this->value = $this->value + $amount;
return $this->value;
}
}
$step = ;
$counter = new Counter();
$first = $counter->add($step);
$second = $counter->add(3);
echo "first=" . $first . "\n";
echo "second=" . $second . "\n";
<?php
class Counter
{
public int $value = 0;
public function add(int $amount): int
{
$this->value = $this->value + $amount;
return $this->value;
}
}
$step = ;
$counter = new Counter();
$first = $counter->add($step);
$second = $counter->add(3);
echo "first=" . $first . "\n";
echo "second=" . $second . "\n";
<?php
class Counter
{
public int $value = 0;
public function add(int $amount): int
{
$this->value = $this->value + $amount;
return $this->value;
}
}
$step = ;
$counter = new Counter();
$first = $counter->add($step);
$second = $counter->add(3);
echo "first=" . $first . "\n";
echo "second=" . $second . "\n";
state changes
Method calls can update stored values, then return a scalar result that the page can display.