PHP中private和public还有protected的区别

public 表示全局,类内部外部子类都可以访问;

private表示私有的,只有本类内部可以使用;

protected表示受保护的,只有本类或子类或父类中可以访问;

//父类

classfather{

publicfunctiona(){

echo"function a";

}

privatefunctionb(){

echo"function b";

}

protectedfunctionc(){

echo"function c";

}

}

//子类

classchildextendsfather{

functiond(){

parent::a();//调用父类的a方法

}

functione(){

parent::c();//调用父类的c方法

}

functionf(){

parent::b();//调用父类的b方法

}

}

$father=newfather();

$father->a();

$father->b();//显示错误 外部无法调用私有的方法 Call to protected method father::b()

$father->c();//显示错误 外部无法调用受保护的方法Call to private method father::c()

$chlid=newchild();

$chlid->d();

$chlid->e();

$chlid->f();//显示错误 无法调用父类private的方法 Call to private method father::b()

你可能感兴趣的:(PHP中private和public还有protected的区别)