Php代碼
<?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; // 這行能被正常執行 echo $obj->protected; // 這行會產生一個致命錯誤 echo $obj->private; // 這行也會產生一個致命錯誤 $obj->printHello(); // 輸出 Public、Protected 和 Private /** * Define MyClass2 */ class MyClass2 extends MyClass { // 可以對 public 和 protected 進行重定義,但 private 而不能 protected $protected = 'Protected2'; function printHello() { echo $this->public; echo $this->protected; echo $this->private; } } $obj2 = new MyClass2(); echo $obj2->public; // 這行能被正常執行 echo $obj2->private; // 未定義 private echo $obj2->protected; // 這行會產生一個致命錯誤 $obj2->printHello(); // 輸出 Public、Protected2 和 Undefined ?>
Php代碼
<?php /** * Define MyClass */ class MyClass { // 聲明一個公有的建構函式 public function construct() { } // 聲明一個公有的方法 public function MyPublic() { } // 聲明一個受保護的方法 protected function MyProtected() { } // 聲明一個私人的方法 private function MyPrivate() { } // 此方法為公有 function Foo() { $this->MyPublic(); $this->MyProtected(); $this->MyPrivate(); } } $myclass = new MyClass; $myclass->MyPublic(); // 這行能被正常執行 $myclass->MyProtected(); // 這行會產生一個致命錯誤 $myclass->MyPrivate(); // 這行會產生一個致命錯誤 $myclass->Foo(); // 公有,受保護,私人都可以執行 /** * Define MyClass2 */ class MyClass2 extends MyClass { // 此方法為公有 function Foo2() { $this->MyPublic(); $this->MyProtected(); $this->MyPrivate(); // 這行會產生一個致命錯誤 } } $myclass2 = new MyClass2; $myclass2->MyPublic(); // 這行能被正常執行 $myclass2->Foo2(); // 公有的和受保護的都可執行,但私人的不行 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(); $myFoo->test(); // Bar::testPrivate // Foo::testPublic ?>
<?phpclass Test{ private $foo; public function construct($foo) { $this->foo = $foo; } private function bar() { echo 'Accessed the private method.'; } public function baz(Test $other) { // We can change the private property: $other->foo = 'hello'; var_dump($other->foo); // We can also call the private method: $other->bar(); }}$test = new Test('test');$test->baz(new Test('other'));?>
以上常式會輸出:
string(5) "hello"
Accessed the private method.