B、便于统一管理属性。
注意:
第一:
__set()和__get()只对私有属性起作用,对于用
public
定义的属性,它们两个都懒理
搭理,如下:
代码如下
:
class
test{
protected
$a
=9,
$b
=2,
$c
;
public
$d
;
function
__set(
$n
,
$v
) {
$this
->
$n
=
$v
+2; }
function
__get(
$name
) {
return
$this
->
$name
+2; }
}
$a
=
new
test();
$a
->b =5;
echo
“<br />”;
echo
$a
->b;
实例只对
$a
,
$b
,
$c
的设置会经过
__set 和__get 过滤与返回,对于
$d
,就不会起作用。如
$a
-
>d=5,再返回还是 5。
第二:
__set(
$n
,
$v
)要带两个参数。而__get(
$n
)只能有一个参数。实例:
代码如下
:
class
test{
private
$a
=5,
$b
=6,
$c
;
function
__set(
$n
,
$v
)
{
if
(
$n
=='a'&&
$n
>0)
$this
->
$n
=
$v
;
else
$this
->
$n
=
$v
+2;
}
function
__get(
$name
)
{
return
$this
->
$name
;
//如果改为 return $this->$name + $this->addab(); 如调用 a 的值,实际返
回的是
a+a+b 的值。默认为 5+5+6=16。
}
function
addab()
{
return
$this
->a +
$this
->b; }
}
$e
=
new
test();
$e
->a = 11;
//注意写法:类的内部用$this->$n 即变量的写法,但外部实例要用$e->a 的方式。
$e
->b = 12;
//get 14
$e
->k = 22;
类的属性可自由扩展,如上例的
k,不管是否用__set,当一个实例建立起来后,可以用
$e
-
>newProperty = xx;直接来创造一个属性,但不建议这么做。