How to Declare and Use Readonly Property in PHP

PHP 8.1 released readonly property which prevents modification of the variable value after initialization. That means properties are initialized once in the constructor, and should not be modified afterwards. 

PHP currently has released these features. In this example, i am going to show you how to declare and use readonly property in PHP. PHP readonly property can only be initialized once, and only from the scope where it has been declared. So any other assignment or modification of the property will result in an Error exception.

Let's see the example code of readonly property:

class User {
    public function __construct(
        public readonly string $name
    ) {}
}

 

Now see its uses:

class Test {
    public readonly string $prop;
 
    public function __construct(string $prop) {
        // Legal initialization.
        $this->prop = $prop;
    }
}
 
$test = new Test("foobar");
// Legal read.
var_dump($test->prop); // string(6) "foobar"
 
// Illegal reassignment. It does not matter that the assigned value is the same.
$test->prop = "foobar";
// Error: Cannot modify readonly property Test::$prop

 

Hope it can help you.

 

Facebook Github
A web enthusiastic, a self-motivated full-stack software engineer from Dhaka, Bangladesh with experience in developing applications using Laravel , React and Vue js