下一篇 » « 上一篇

php4和php5区别

作者:    时间:2008-02-23    来源:    点击:7664    本文共13篇文章 字体:[ ]

对象中的私有、公共及保护模式

PHP4 中,一个对象的所有方法和变量都是公共的,这意味着你可以在一个对象的外部操作其中的任意一个变量和方法.PHP5 引入了三种新的用来控制这种存取权限的模式,它们是:公共的(Public)、受保护的(Protected)及私有的(Private).

本文来自 www.444p.com

公共模式(Public):允许在对象外部进行操作控制.
私有模式(Private):只允许本对象内的方法对其进行操作控制.
受保护模式(Protected):允许本对象及其父对象对其进行操作控制.

php学习之家

例四: 对象中的私有、公共及受保护模式

php学习之家http://www.444p.com

PHP代码
  1. <?   
  2. class foo {    
  3.     private $x;    
  4.     public function public_foo() {    
  5.         print("I'm public");    
  6.     }   
  7.     protected function protected_foo() {    
  8.         $this->private_foo(); //Ok because we are in the same class we can call private methods    
  9.         print("I'm protected");    
  10.     }   
  11.     private function private_foo() {    
  12.         $this->x = 3;    
  13.         print("I'm private");    
  14.     }    
  15. }   
  16. class foo2 extends foo {    
  17.     public function display() {    
  18.         $this->protected_foo();    
  19.         $this->public_foo();    
  20.         // $this->private_foo(); // Invalid! the function is private in the base class    
  21.     }   
  22. }   
  23. $x = new foo();   
  24. $x->public_foo();   
  25. //$x->protected_foo(); //Invalid cannot call protected methods outside the class and derived classes    
  26. //$x->private_foo(); //Invalid private methods can only be used inside the class $x2 = new foo2();    
  27. $x2->display();   
  28. ?>  

提示:对象中的变量总是以私有形式存在的,直接操作一个对象中的变量不是一个好的面向对象编程的习惯,更好的办法是把你想要的变量交给一个对象的方法去处理.

  • php4和php5区别 上一页 对象的克隆
  • php4和php5区别 总目录
  • php4和php5区别 下一页 接口 (Interfaces)
责任编辑:semirock
发表评论
密码: (游客不需要密码)
记住我【Alt+S 或 Ctrl+Enter 快速提交】

搜索工具


《PHP教程》点击排行