如果获取->属性 php会自动调用这个方法
<?php class Stuendent{ private $name; public function __set($name,$value){ if (property_exists($this, $name)) { $this->$name = $value; }else { throw new \Exception("没有这个私有变量属性", 1); } } public function __get($name){ return $this->$name."__get"; } } $st = new Stuendent; // 实例化 $st->name = "songhao"; print_r($st); echo $st->name;
|
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
Stuendent
{
private
$
name
;
public
function
__set
(
$
name
,
$
value
)
{
if
(
property_exists
(
$
this
,
$
name
)
)
{
$
this
->
$
name
=
$
value
;
}
else
{
throw
new
\
Exception
(
"没有这个私有变量属性"
,
1
)
;
}
}
public
function
__get
(
$
name
)
{
return
$
this
->
$
name
.
"__get"
;
}
}
$
st
=
new
Stuendent
;
/
/
实例化
$
st
->
name
=
"songhao"
;
print_r
(
$
st
)
;
echo
$
st
->
name
;
|
你如果不想用 __get 获取所有类的属性
<?php class Stuendent{ private $white_array = ['<span class="wp_keywordlink"><a href="http://www.168seo.cn/python" title="python">python</a></span>']; private $name; private $<span class="wp_keywordlink"><a href="http://www.168seo.cn/python" title="python">python</a></span>='I can write Python code'; public function __set($name,$value){ if (property_exists($this, $name)) { $this->$name = $value; }else { throw new \Exception("没有这个私有变量属性", 1); } } public function __get($name){ if(in_array($name, $this->white_array)){ // 检测这个属性值 是否在white_array这个属性里面 // 如果在 则返回这个值,如果不在就返回null return $this->$name."__get"; }else { return null; } } } $st = new Stuendent; // 实例化 $st->name = "songhao"; echo $st->name; // 无输出 echo $st-><span class="wp_keywordlink"><a href="http://www.168seo.cn/python" title="python">python</a></span>;
|
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
Stuendent
{
private
$
white_array
=
[
'python'
]
;
private
$
name
;
private
$
python
=
'I can write Python code'
;
public
function
__set
(
$
name
,
$
value
)
{
if
(
property_exists
(
$
this
,
$
name
)
)
{
$
this
->
$
name
=
$
value
;
}
else
{
throw
new
\
Exception
(
"没有这个私有变量属性"
,
1
)
;
}
}
public
function
__get
(
$
name
)
{
if
(
in_array
(
$
name
,
$
this
->
white_array
)
)
{
/
/
检测这个属性值
是否在
white
_array这个属性里面
/
/
如果在
则返回这个值,如果不在就返回
null
return
$
this
->
$
name
.
"__get"
;
}
else
{
return
null
;
}
}
}
$
st
=
new
Stuendent
;
/
/
实例化
$
st
->
name
=
"songhao"
;
echo
$
st
->
name
;
/
/
无输出
echo
$
st
->
python
;
|
输出结果:

被折叠的 条评论
为什么被折叠?



