型アクセス修飾子を使用すると、開発者はクラス メンバーへのアクセスを制限できます。これは 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?>