class dome{
private $age;
public function __construct($age){
$this->age =$age;
}
public function __set ($name,$value){
if($name =='age')
{return false;}
return $this->$name= $value;
}
}
$obj =new dome(24);
echo $obj->age=25;and
$obj->age=26;
$obj->age=26;; In both cases, the output results should be the default value 24, but the result of
echo $obj->age=25 is 25. Age has been modified? $obj->age=26; echo $obj-> ;age; There is no problem with this sentence. Do they have different meanings?
In your code, the second echo should not be executed. You didn’t post the entire code, because it will prompt you that you cannot access private properties
The difference between the two output results is because of the way you write echo, echo a = 3 This way of writing will execute the assignment statement, but regardless of whether the assignment is successful, the number to the right of the equal sign will be output to the screen
1. The first echo $obj->age=25; executes your set method , it is obtained that name is equal to age, and return false is executed, so the value of the attribute age is not modified. But with your way of writing, it will output the 25 on the right side of your equal sign on the screen;
2. The second way is the normal way of writing, which will execute the assignment statement, then judge and return false, without modifying the value of age, and then Output the value of your age attribute is still 24
echo $obj->age=25 This statement is wrong. You did not change the value in the class. You just output a value of 25.
1. There should be something wrong in your set method. Look at your else statement, it seems like it’s missing
2. If you want to read private attributes, you need to write another get method