php访问控制
/**
燕十八 公益PHP培训
课堂地址:YY频道88354001
学习社区:www.zixue.it
**/
对属性或方法的访问控制,是通过在前面添加关键字public protected private来实现的。由public所定义的类成员可以在任何地方被访问;由protected所定义的类成员则可以被其所在类的子类和父类访问,(该成员所在的类也可以访问),由private定义的类成员只能被其所在的类访问
例如:
<?php
class Myclass{
public $public='public';
protected $protected='protected';
private $private='private';
function print_hello(){
echo $this->public.'<br/>';
echo $this->protected.'<br/>';
echo $this->private.'<br/>';
}
}
$obj=new Myclass();
//echo $obj->public;//public
//echo $obj->protected;// Undefined property: Myclass::$protected
//echo $obj->private;//Cannot access protected property Myclass::$protected
//$obj->print_hello();
class Myclass2 extends Myclass{
protected $protected="protected2";
public function print_hello(){
echo $this->public;
echo $this->protected;
echo $this->private;
}
}
$obj2=new Myclass2();
//echo $obj->public;//public
//echo $obj2->private;//Undefined property: Myclass2::$private 没有定义
//echo $obj2->protected;//Cannot access protected property Myclass2::$protected
?>
重写方法的规则
- 方法名和参数必须一致
class p{
public function getName(){}
}
class c extends p{
public function getName(){}
}
- final方法不能重写
- 私用方法不能重写,因为私有方法不可见对于子类
class a {
private function my(){
print "parent:my";
}
public function getmy(){
$this->my();
}
}
class b extends a{
private function my(){
print "base:my";
}
}
$x = new b();
$x->getmy(); // parent:my
- 降低访问权限不可以重写
class a {
public function my(){
print "parent:my";
}
}
class b extends a{
private function my(){
print "base:my";
}