Magic method __set ()

__set () action:

 

__set (): When to inaccessible property assignment (private, protected, does not exist), php will perform __set () method. Marble repair factory mechanical member

Above we said __set () role is: when to inaccessible property assignment (private, protected, does not exist), php will perform __set () method.

This is what this means. For example, we were still examples of the above example. We like to eat peaches into monkeys bananas, but according to the rules for, $ food in front of the keyword is protected
, can not be accessed directly, but we need to assign $ food, how can we do it?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

<?php

class Monkey{

public $name;

protected $food;

function __construct($name,$food){

$this->name = $name;

$this->food = $food;

}

function sayHello(){

echo '<br/>我是' . $this->name . '我喜欢吃' . $this->food;

}

//魔术方法

function __get($pro_name){

//先判断$pro_name是否存在

if(isset($this -> $pro_name)){

return $this -> $pro_name;

}else{

echo '属性值不存在';

}

}

function __set($pro_name,$value){

//先判断$pro_name是否存在

if(isset($this -> $pro_name)){

return $this -> $pro_name = $value;

}else{

echo '属性值不存在';

}

$monkey = new Monkey('猴子' , '桃子')

$monkey -> sayHello();

echo '猴子喜欢吃' . $monkey -> food;

$monkey -> food = '香蕉';

echo '<br/>';

$monkey -> sayHello();

Because our $ food is protected, it does not allow access. So, we will help __set () magic methods. the __set () method includes two parameters, respectively, variable names and variable values, two parameters can not be omitted. https://www.bzddrive.com/zxmzcj/1294.html

Guess you like

Origin www.cnblogs.com/furuihua/p/12167670.html