Home >Backend Development >PHP Tutorial >Sample code sharing for oop6 visibility control in php5
Like other languages, it is also restricted by the keywords public, protected, and private:
<?php /** * 定义MyClass */ class MyClass { public $public = 'Public';//公有 protected $protected = 'Protected';//保护 private $private = 'Private';//私有 function printHello() { echo $this->public;echo "<br/>"; echo $this->protected;echo "<br/>"; echo $this->private;echo "<br/>"; } } $obj = new MyClass(); echo $obj->public; // 可以 //echo $obj->protected; // 致命错误 //echo $obj->private; // 致命错误 $obj->printHello(); // 输出 Public, Protected and Private /** * 定义 MyClass2 */ class MyClass2 extends MyClass { // 对于公有和保护方法或成员,我们可以重新声明,但私有的不可以 protected $protected = 'Protected2'; //重写 function printHello() { echo "这个是MyClass2的:";echo "<br/>"; echo $this->public;echo "<br/>"; echo $this->protected;echo "<br/>"; //echo $this->private;echo "<br/>";不能访问到父类的私有属性 } } $obj2 = new MyClass2(); echo $obj2->public; // 可以 //echo $obj2->private; // 未定义 //echo $obj2->protected; // 致命错误 $obj2->printHello(); // 输出 Public, Protected2, Undefined ?>
Of course, through these access control characters, we can also functionAchieve the same access control:
<?php /** * 定义 MyClass */ class MyClass { // 构造函数必须是public public function construct() { } // 声明一个public 的方法 public function MyPublic() { } // 声明 protected 方法 protected function MyProtected() { } // 声明private 方法 private function MyPrivate() { } // 默认是public的 function Foo() { //类里面可以直接访问 $this->MyPublic(); $this->MyProtected(); $this->MyPrivate(); } } $myclass = new MyClass; $myclass->MyPublic(); // 可以 $myclass->MyProtected(); // 致命错误 $myclass->MyPrivate(); //致命错误 $myclass->Foo(); /** * 定义 MyClass2 */ class MyClass2 extends MyClass { //public function Foo2() { $this->MyPublic(); $this->MyProtected(); $this->MyPrivate(); // 致命错误 } } $myclass2 = new MyClass2; $myclass2->MyPublic(); // 可以 $myclass2->Foo2(); /** * 定义Bar */ class Bar { public function test() { $this->testPrivate(); $this->testPublic(); } public function testPublic() { echo "Bar::testPublic\n"; } private function testPrivate() { echo "Bar::testPrivate\n"; } } class Foo extends Bar { public function testPublic() { echo "Foo::testPublic\n"; } private function testPrivate() { echo "Foo::testPrivate\n"; } } $myFoo = new Foo(); //通过继承来的公有方法Bar::test() $myFoo->test(); // Bar::testPrivate // Foo::testPublic ?>
The above is the detailed content of Sample code sharing for oop6 visibility control in php5. For more information, please follow other related articles on the PHP Chinese website!