J
J
JackShcherbakov2018-03-01 21:10:45
PHP
JackShcherbakov, 2018-03-01 21:10:45

Why is the access method not working?

Hello!
This code should not allow the return to be set to less than 20, but any value can be set - a mess. How to fix?

<?php
class Car{
  public $age = 30;

  function __set($name, $value){
    if($value>20){ //Возвраст может быть только больше 20-и
      $this->$name = $value;
    }
  }
}
$car = new Car();
$car->age = 15; //Такого делать нельзя!
echo $car->age;
?>

Why is __set() a magic method? What is the name from? What is its feature?
There's a contradiction in the book I'm reading

Accessors do not apply to private properties.
The following statement will implicitly call the __set() function:
$a->attribute = 5;

Well, how will the __set() function be called if we access a public (public) property?
Nothing is clear. The documentation is also nonsense. Some magic methods...
Thanks in advance!

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question