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

PHP
php 清除网页病毒的方法
php 远程关机操作的代码
Zend Studio for Eclipse的java.lang.NullPointerException错误的解决方法
PHP 出现乱码和Sessions验证问题的解决方法!
php2html php生成静态页函数
中英文字符串翻转函数
php escape URL编码
PHP Google的translate API代码
php 文件状态缓存带来的问题
linux下 C语言对 php 扩展
php mssql 数据库分页SQL语句
php IP及IP段进行访问限制的代码
PHP 采集程序 常用函数
php 设计模式之 单例模式
php 设计模式之 工厂模式
php xml-rpc远程调用
php 获取完整url地址
PHP MSSQL 存储过程的方法
PDP Document 代码注释规范
PHP HTML代码串截取代码

PHP 面向对象的方法重载


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