PHP中的public、protected与private修饰符

星期三, 9月 30, 2009 | 1分钟阅读 | 更新于 星期三, 9月 30, 2009

@

public:方法或者属性在任何作用域都可以访问到,而且这是默认的,如果没有为一个属性或方法指定访问修饰符,它将是public。

protected:方法或者属性只能从类或者继承类的一个成员中访问到。

private:方法或者属性只能从类的一个成员中访问到,而且无法从继承类的成员中访问到。经过private便签标记的方法或者属性可以在继承类中重新定义。每一个类只能看到它自己定义的私有方法。

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;
// Works
echo $obj->protected;
// Fatal Error
echo $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;
// Works
echo $obj2->private;
// Undefined //私有属性可以重新定义,但MyClass2里面没有定义
echo $obj2->protected;
// Fatal Error //受保护的属性不能重新定义
$obj2->printHello();
// Shows Public, Protected2, not Private
comments powered by Disqus

© 2018 - 2025 DiyBeta's Blog

Powered by Hugo & Dream

Me

Cut out summary from your post content here.

The remaining content of your post.