Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

read-only properties in PHP?

Tags:

oop

php

readonly

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.

like image 948
user151841 Avatar asked Aug 30 '10 13:08

user151841


1 Answers

If you're using PHP 5+ you can do it with __set() and __get() methods.

You have to define how they work but should do just this.

Edit an example would be like this.

class Example {
    private $var;
    public function __get($v) {
        if (is_array($v)) {
            foreach () {
                // handle it here
            }
        } else {
            return $this->$v;
        }
    }
}

This might not be the "best" way of doing it but it'll work depending on what you need

like image 97
Viper_Sb Avatar answered Sep 19 '22 11:09

Viper_Sb