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

PHP
MYSQL版本大于4.1问题 - PHPchina
怎么让用户点击一个连接后,把一个图片另存了 - PHPchina
武汉10月15日Phper聚会召集!!! - PHPchina
php如果不等待exec执行的程序创建的子进程? - PHPchina
哪位知道DISCUZ处理防SQL注入的代码是哪部分 - PHPchina
求教!我实在不知道哪里问题,在线等ing - PHPchina
怎样结束用户某一进程 - PHPchina
比对用户名密码能不能这样写? - PHPchina
求助:如何在PHP+mysql中实现数据备份? - PHPchina
大家看看这个配置对吗 - PHPchina
如何禁止require当前文件 - PHPchina
无法将回调函数放在类中? - PHPchina
村里 PHP代码高亮是怎么实现的? - PHPchina
apache安装后.服务里没有apache2这个服务! - PHPchina
请教一个小问题 - PHPchina
config.php里面是不是应该把多数参数设置为常量而不是变量? - PHPchina
请教高手一个问题 - PHPchina
如何让百度收录我的网站 ?? - PHPchina
谁能给个注入的简单语句? - PHPchina
求PHP站内搜索思路 - PHPchina

PHP 面向对象的方法重载


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