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

PHP
php zlib压缩和解压缩swf文件的代码
PHP 常用函数库和一些实用小技巧
php 时间计算问题小结
php 禁止页面缓存输出
PHP 地址栏信息的获取代码
据说是雅虎的一份PHP面试题附答案
PHP setcookie() cannot modify header information 的解决方法
Google PR查询接口checksum新算法
php zend 相对路径问题
php mssql 时间格式问题
php str_pad 函数使用详解
php strtotime 函数UNIX时间戳
php array_intersect()函数使用代码
PHP mkdir()定义和用法
php array_flip() 删除数组重复元素
php完全过滤HTML,JS,CSS等标签
php 删除数组元素
PHP $_SERVER详解
php 动态多文件上传
防止MySQL注入或HTML表单滥用的PHP程序

PHP 面向对象的方法重载


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