Visibility and Constructors
Getter Method
A getter method exposes a private value without exposing direct writes.
Getter Method
getter_method.php
<?php
class Account
{
public function __construct(private int $balance)
{
}
public function balance(): int
{
return $this->balance;
}
}
$start = ;
$balance = (new Account($start))->balance();
echo "start=" . $start . "\n";
echo "balance=" . $balance . "\n";
<?php
class Account
{
public function __construct(private int $balance)
{
}
public function balance(): int
{
return $this->balance;
}
}
$start = ;
$balance = (new Account($start))->balance();
echo "start=" . $start . "\n";
echo "balance=" . $balance . "\n";
<?php
class Account
{
public function __construct(private int $balance)
{
}
public function balance(): int
{
return $this->balance;
}
}
$start = ;
$balance = (new Account($start))->balance();
echo "start=" . $start . "\n";
echo "balance=" . $balance . "\n";
controlled read
The object can keep its stored value private while still returning a scalar value.