Back to questions
JuniorTheoryCommon
What happens when you run this program?
<?php
class Account
{
public function __construct(private int $balance) {}
}
$acc = new Account(50);
echo 'ok', "\n";
echo $acc->balance, "\n";ok, then an Error: cannot access private property
- Expecting
50, as if promotion made the property public:private int $balancedeclares aprivateproperty, and reading it outsideAccountthrows anError. - Expecting a Warning and an empty value: a
privateproperty is not a missing one, so reading it from outside throws anErrorand stops the script.
- How would you let outside code read the balance without letting it change the balance?
- Which code may read
$this->balancewithout an error?