PHP4 中,一个对象的所有方法和变量都是公共的,这意味着你可以在一个对象的外部操作其中的任意一个变量和方法.PHP5 引入了三种新的用来控制这种存取权限的模式,它们是:公共的(Public)、受保护的(Protected)及私有的(Private).
本文来自 www.444p.com
公共模式(Public):允许在对象外部进行操作控制.
私有模式(Private):只允许本对象内的方法对其进行操作控制.
受保护模式(Protected):允许本对象及其父对象对其进行操作控制.
例四: 对象中的私有、公共及受保护模式
php学习之家http://www.444p.com
PHP代码
- <?
- class foo {
- private $x;
- public function public_foo() {
- print("I'm public");
- }
- protected function protected_foo() {
- $this->private_foo(); //Ok because we are in the same class we can call private methods
- print("I'm protected");
- }
- private function private_foo() {
- $this->x = 3;
- print("I'm private");
- }
- }
- class foo2 extends foo {
- public function display() {
- $this->protected_foo();
- $this->public_foo();
- // $this->private_foo(); // Invalid! the function is private in the base class
- }
- }
- $x = new foo();
- $x->public_foo();
- //$x->protected_foo(); //Invalid cannot call protected methods outside the class and derived classes
- //$x->private_foo(); //Invalid private methods can only be used inside the class $x2 = new foo2();
- $x2->display();
- ?>
提示:对象中的变量总是以私有形式存在的,直接操作一个对象中的变量不是一个好的面向对象编程的习惯,更好的办法是把你想要的变量交给一个对象的方法去处理.



















