欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

php类对象中__get()和__set()方法使用教程

程序员文章站 2022-04-09 10:00:00
...
问1:

class Test{

private $aa=1;

function __get($proName){return $this->proName;}

}

class subTest extends Test{

private $aa=2;

}

$test=new subTest();

echo $test->aa;

求解释,为啥输出1?

答:当试图从类的外部访问私有属性时,__get方法会被调用,如果它存在的话subTest继承了Test类,并试图重载aa,但是没有__get()方法,当实例化subTest类后访问它的私有属性,由于__get()方法,所以默认将调用父类的__get方法,当然访问的也是父类的aa属性,如果要输出2可以为subTest类添加__get()

追问:那继承父类的方法能不能访问子类的成员属性

class Test{

protected $aa=1; function __get($proName){return $this->$proName;}

}

class subTest extends Test{

protected $aa=2;

}

$test=new subTest();

echo $test->aa;

答:这里输出2,因为子类覆盖了从父类继承来的属性aa,因为他们都是protected的,所以可以覆盖

追问:

class Test{

private $aa=1;

function __get($proName){

return $this->$proName;

}

class subTest extends Test{

protected $aa=2;

}

$test=new subTest();

echo $test->aa;

答:这次输出1,是因为子类并没有覆盖父类的属性而且没有自己的__get方法,当访问同一个属性时,php默认将其识别为private,也就是以父类的访问限定符为标准,识别private后就会调用__get()方法,所以输出1

对应的__set()是设置属性的值,原理相似。