php魔术方法

    在 PHP 中以两个下划线开头的方法,__construct(), __destruct (), __call(), __callStatic(),__get(), __set(), __isset(), __unset (), __sleep(), __wakeup(), __toString(), __set_state,() __clone() __autoload()等,被称为"魔术方法",

    魔术方法必须在类中定义。

  

__set()方法

 
当程序试图写入一个不存在或者封装的成员变量时,执行__set()方法。__set()方法包含两个参数,分别表示变量名称和变量值,两个参数都不可省略。
例1:
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
<?php
class SportObject{
private $type='';
public function __get($name){
if(
isset($this->$name)){
echo'变量'.$name.'的值为:'.$this->$name.'<br>';
}else{
echo'变量'.$name.'未定义,初始化为0<br>';
$this->$name=0;
}
}
public function __set($name,$value){
if(
isset($this->$name)){
$this->$name=$value;
echo'变量'.$name.'赋值为:'.$value.'<br>';
}else{
$this->$name=$value;
echo'变量'.$name.'被初始化为:'.$value.'<br>';
}
}
}
$MyComputer=newSportObject();
$MyComputer->type='DIY';
$MyComputer->type;
?>
例1输出结果为:
变量type赋值为:DIY
变量type的值为:DIY
 

__get()方法

简介:
当程序试图调用一个未定义或封装的成员变量时,可以通过__get()方法来读取变量值。__get()方法有一个参数,表示要调用的变量名。
例2:
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
<?php
class SportObject{
private $type='';
public function__get($name){
if(
isset($this->$name)){
echo'变量'.$name.'的值为:'.$this->$name.'<br>';
}else{
echo'变量'.$name.'未定义,初始化为0<br>';
$this->$name=0;
}
}
public function __set($name,$value){
if(
isset($this->$name)){
$this->$name=$value;
echo'变量'.$name.'赋值为:'.$value.'<br>';
}else{
$this->$name=$value;
echo'变量'.$name.'被初始化为:'.$value.'<br>';
}
}
}
$MyComputer=newSportObject();
$MyComputer->name;
?>
例2输出结果为:
变量name未定义,初始化为0
变量name被初始化为:0
原文地址:https://www.cnblogs.com/du892294464/p/6730939.html