⊗ppOpMgROP 89 of 107 menu

Read-Only Properties in OOP in PHP

Let's consider a class in which all properties are private:

<?php class Test { private $prop1 = 1; private $prop2 = 2; } ?>

Now let's make it so that these properties in the external world are available only for reading. We have done this before by creating getters for each property and not creating setters.

Let's now use the magic method __get to solve this task. We will return the value of the requested property in it. How to do it: the name of the requested property gets into the parameter of the method __get, in our case $property.

This means that we can read the property, the name of which is stored in a variable, like this: $this->$property (the property name will be a variable, that is, with a dollar sign at the beginning, we covered this in previous lessons).

Let's create the described method __get:

<?php class Test { private $prop1 = 1; private $prop2 = 2; public function __get($property) { return $this->$property; } } ?>

Let's use it to read properties:

<?php $test = new Test; echo $test->prop1; // will output 1 echo $test->prop2; // will output 2 ?>

An attempt to write something to the property will lead to an error:

<?php $test = new Test; $test->prop1 = 2; // will give an error ?>

This is exactly what we need: the property can be read, but cannot be written to.

An attempt to read a non-existent property will give an error:

<?php $test = new Test; echo $test->prop3; // will give an error ?>

Also pay attention to the following nuance: when we made properties read-only using the old method, to read the property, we used a getter method.

In the new method, we will access the properties directly, as if they were public. But we won't be able to write to them, as if they were private.

Given the following class User, whose properties are available only for reading using getters:

<?php class User { private $name; private $age; public function __construct($name, $age) { $this->name = $name; $this->age = $age; } public function getName() { return $this->name; } public function getAge() { return $this->age; } } ?>

Rewrite the code of this class so that instead of getters, the magic method __get is used.

azbydeenesfrkakkptruuz