首页 > 后端开发 > php教程 > php面向对象(OOP 编程)- 类访问修饰符

php面向对象(OOP 编程)- 类访问修饰符

WBOY
发布: 2016-06-20 12:30:17
原创
1115 人浏览过

类型的访问修饰符允许开发人员对类成员的访问进行限制,这是PHP5的新特性


private
protected public
同一个类中
类的子类中  
所有的外部成员    

<?php/** * 类属性访问控制 * Define MyClass */class MyClass{	public $public = 'Public';	protected $protected = 'Protected';	private $private = 'Private';	function printHello()	{		echo $this->public;		echo $this->protected;		echo $this->private;	}}$obj = new MyClass();echo $obj->public;		// Worksecho $obj->protected;	// Fatal Errorecho $obj->private;		// Fatal Error$obj->printHello();		// Shows Public, Protected and Private/** * Define MyClass2 */class MyClass2 extends MyClass{	// We can redeclare the public and protected method, but not private	protected $protected = 'Protected2';	function printHello()	{		echo $this->public;		echo $this->protected;		echo $this->private;	}}$obj2 = new MyClass2();echo $obj->public;		// Worksecho $obj2->private;	// Undefinedecho $obj2->protected;	// Fatal Error$obj2->printHello();	// Shows Public, Protected2, not Private?>
登录后复制



<?php/** * 类方法访问控制 * Define MyClass */class MyClass{	// Contructors must be public	public function __construct() { }	// Declare a public method	public function MyPublic() { }	// Declare a protected method	protected function MyProtected() { }       //abstract protected function funProtect($param);抽象方法只能在抽象类中定义	// Declare a private method	private function MyPrivate() { }    	// This is public	function Foo()	{		$this->MyPublic();		$this->MyProtected();		$this->MyPrivate();	}}$myclass = new MyClass;$myclass->MyPublic();		// Works$myclass->MyProtected();	// Fatal Error$myclass->MyPrivate();		// Fatal Error$myclass->Foo();			// Public, Protected and Private work/** * Define MyClass2 */class MyClass2 extends MyClass{	// This is public	function Foo2()	{		$this->MyPublic();		$this->MyProtected();		$this->MyPrivate();		// Fatal Error	}}$myclass2 = new MyClass2;$myclass2->MyPublic();	// Works$myclass2->Foo2();		// Public and Protected work, not Private?>
登录后复制




来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板