How to create a read-only property in a class in PHP?

Question:

In the following example you can see how to create a public property, this would allow me to read and write the variable, but I want it to only be read.

<?php
class Test{
    public $luckNumber = 51;
}

$obj = new Test();

//No debe ser posible asignar a esta propiedad
$obj->luckNumber = 42;

echo $obj->luckNumber; //51

Answer:

You can create a read-only property in two ways:

1) Using access modifiers

Change access from public to private and create a method that returns the property's value.

Example:

class Test{
    private $luckNumber = 51;

    public function getLuckNumber(){
        return $this->luckNumber;
    }
}

$t = new Test();
echo $t->getLuckNumber(); //51

2) Using the __set() method

Change access from public to private and implement the __set() method, which will check if the property is rewritten and return an error / throw an exception if it is read-only.

Example:

class Test{
    private $luckNumber = 51;

    public function __set($name, $value){
        if($name == 'luckNumber'){
            trigger_error("can't write a ready only property", E_USER_ERROR );
            //throw new Exception('wow');
        }
    }
}

$t = new Test();

$t->luckNumber = 42; //error
echo $t->luckNumber; //51

More information about this method in PHP – __set () & magic methods .

Scroll to Top