当前位置: 首页 > 图文教程 > 网络编程 > PHP > PHP 面向对象的方法重载

PHP
PHP新手总结的PHP基础知识
php实现gb2312和unicode间编码转换
用php语言实现数据库连接详细代码介绍
详细解析 PHP 向 MySQL 发送数据过程
利用PHP V5开发多任务应用程序
详细讲解PHP中缓存技术的应用
php escapeshellcmd多字节编码漏洞
《PHP设计模式介绍》导言
《PHP设计模式介绍》第一章 编程惯用法
《PHP设计模式介绍》第二章 值对象模式
《PHP设计模式介绍》第三章 工厂模式
《PHP设计模式介绍》第四章 单件模式
《PHP设计模式介绍》第五章 注册模式
《PHP设计模式介绍》第六章 伪对象模式
《PHP设计模式介绍》第七章 策略模式
《PHP设计模式介绍》第八章 迭代器模式
《PHP设计模式介绍》第九章 观测模式
《PHP设计模式介绍》第十章 规范模式
《PHP设计模式介绍》第十一章 代理模式
《PHP设计模式介绍》第十二章 装饰器模式

PHP 面向对象的方法重载


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-09-23   浏览: 104 ::
收藏到网摘: n/a

“重载”是类的多态的一种实现。函数重载指一个标识符被用作多个函数名,且能够通过函数的参数个数或参数类型将这些同名的函数区分开来,调用不发生混淆。这样做的主要好处就是,不用为了对不同的参数类型或参数个数,而写多个函数。多个函数用同一个名字,但参数表,即参数的个数或(和)数据类型可以不同,调用的时候,虽然方法名字相同,但根据参数表可以自动调用对应的函数。

PHP4 中仅仅实现了面向对象的部分的、简单的功能,而 PHP5 以后对对象的支持就强大的多了。

对于多态的实现,PHP4 只支持覆盖(override),而不支持重载(overload)。但我们可以通过一些技巧来“模拟”重载的实现。

PHP5 虽然可以支持覆盖和重载,但重载在具体实现上,和其他语言还有较大的差别。

1,在 PHP4 中“模拟”重载

试看以下代码:

以下为引用的内容:

  <?php
  //根据参数个数选择执行不同的方法(在 PHP4 中模拟"重载"(多态的一种)
  class Myclass
  {
  function Myclass()
  {
  $method = "method" . func_num_args();
  $this->$method();
  }
  function method1($x)
  {
  echo "method1";
  }
  function method2($x, $y)
  {
  echo 'method2';
  }
  }
  //通过在类中的额外的处理,使用这个类对用户是透明的:
  $obj1 = new Myclass('A'); //将调用 method1
  $obj2 = new Myclass('B','C'); //将调用 method2
  ?>

以上代码中,通过在构造函数中使用 func_num_args() 函数取到参数的个数,自动执行 method1 或  method2 方法。我们可以结合函数 func_get_arg(i) 和 func_get_args() 对以上示例进行改进。

2,在 PHP5 中使用重载
先看以下示例:

以下为引用的内容:

  <?php
  class Myclass
  {
  public $attriable;
  public $one = "this is one";
  public $two = "this is two";
  function __construct()
  {
  }
  function one($one)
  {
  $this->one=$one;
  $this->attriable = $this->one;
  }
  function one($one, $two)
  {
  $this->one=$one;
  $this->two=$two;
  $this->attriable = $this->one . $this->two;
  }
  function display()
  {
  echo $this->attriable;
  }
  }
  $one = "this is my class";
  $two = "Im the best";
  $myclass = new myclass();
  $myclass->one($one);
  $myclass->display();
  $myclass->one($one, $two);
  $myclass->display();
  //本例的做法,在 PHP 中是不正确的!
  ?>