Rumah  >  Artikel  >  pembangunan bahagian belakang  >  php面向对象(OOP 编程)- 类访问修饰符

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

WBOY
WBOYasal
2016-06-20 12:30:171112semak imbas

类型的访问修饰符允许开发人员对类成员的访问进行限制,这是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?>




Kenyataan:
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn