Writing Properties Through Magic in OOP in PHP
The magic method __set is called
when trying to change the value of a non-existent
or hidden property. It accepts the property name
and the value that is trying to be assigned to it as parameters.
Let's look at a practical example.
Suppose we have a Test class like this:
<?php
class Test
{
private $prop1;
private $prop2;
}
?>
Let's create a magic method __set in this class,
which will use the var_dump function
to output the name of the property
that was accessed and the value
that is trying to be set for it:
<?php
class Test
{
private $prop1;
private $prop2;
public function __set($property, $value)
{
var_dump($property . ' ' .$value);
}
}
?>
Let's test our class:
<?php
$test = new Test;
$test->prop = 'value'; // __set method's var_dump will output 'prop value'
?>
Now let's set the value
for the property whose name is stored in the variable
$property:
<?php
class Test
{
private $prop1;
private $prop2;
public function __set($property, $value)
{
$this->$property = $value; // set the value
}
}
?>
Now we can write to private properties from outside the class:
<?php
$test = new Test;
$test->prop1 = 1; // write 1
$test->prop2 = 2; // write 2
?>
We can write, however, we cannot check if anything was written there, since the properties are private.
We can create a getter for these properties or
just use the magic method
__get. Let's use the second option:
<?php
class Test
{
private $prop1;
private $prop2;
public function __set($property, $value)
{
$this->$property = $value;
}
// Magic property getter:
public function __get($property)
{
return $this->$property;
}
}
?>
Now we can test our class. Let's test it:
<?php
$test = new Test;
$test->prop1 = 1; // write 1
$test->prop2 = 2; // write 2
echo $test->prop1; // will output 1
echo $test->prop2; // will output 2
?>
Of course, in reality, you shouldn't allow everyone to write to private properties, otherwise, the point of these private properties is lost (it's easier to just make them public).
Therefore, this method should only be used when there is a real need for it. In the next lessons, we will look at examples of successful application.