read-only properties in PHP?

Viewed 18927

Is there a way to make a read-only property of an object in PHP? I have an object with a couple arrays in it. I want to access them as I normally would an array

echo $objObject->arrArray[0];

But I don't want to be able to write to those arrays after they're constructed. It feels like a PITA to construct a local variable:

$arrArray = $objObject->getArray1();
echo $arrArray[0];

And anyways, while it keeps the array in the object pristine, it doesn't prevent me from re-writing the local array variable.

5 Answers

For PHP 8.1+, you can use readonly properties:

class Test
{
    public readonly array $arrArray;

    public function __construct()
    {
          $this->arrArray = [1, 2, 3];
    } 
}

$test = new Test();
var_dump($test->arrArray); // OK
$test->arrArray = [4, 5, 6]; // Error
Related