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

PHP
PHP XML操作类DOMDocument
php jquery 实现新闻标签分类与无刷新分页
php 来访国内外IP判断代码并实现页面跳转
php 计算两个时间戳相隔的时间的函数(小时)
php 日期时间处理函数小结
PHP strtotime函数详解
PHP 抓取新浪读书频道的小说并生成txt电子书的代码
php 空格,换行,跳格使用说明
c#中的实现php中的preg_replace
PHP 分页原理分析,大家可以看看
php 8小时时间差的解决方法小结
PHP 源代码压缩小工具
php 常用类整理
在PHP中检查PHP文件是否有语法错误的方法
PHP simple_html_dom.php+正则 采集文章代码
PHP array_push 数组函数
php 文章采集正则代码
php 需要掌握的东西 不做浮躁的人
phpMyAdmin链接MySql错误 个人解决方案
PHP 获取目录下的图片并随机显示的代码

PHP 面向对象的方法重载


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-09-23   浏览: 112 ::
收藏到网摘: 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 中是不正确的!
  ?>