您现在的位置: 网页制作教程网 >> 网络编程 >> php 教程 >> PHP 开发技巧 >> 文章正文

PHP V5 迁移指南

作者:动态网站…

来源:动态网站制作指南

热度:

2006-12-8 8:51:12

将这个类转换为 PHP V5 的第一步是要将构造程序重命名。在 PHP V5 中,初始化对象 (构造程序) 的方法称为 __construct。这次小改动如下所示。


清单 2. access1.php5

<?php
class Configuration
{
  var $_items = array();

  function __construct() {
    $this->_items[ 'imgpath' ] = 'images';
  }
  function get( $key ) {
    return $this->_items[ $key ];
  }
}

$c = new Configuration();
echo( $c->get( 'imgpath' )."\n" );
?>
 


这次改动并不大。只是移至 PHP V5 约定。下一步是添加对类的访问控制以确保类的使用者无法直接读写 $_items 成员变量。这次改动如下所示。


清单 3. access2.php5

<?php
class Configuration
{
  private $_items = array();

  public function __construct() {
    $this->_items[ 'imgpath' ] = 'images';
  }
  public function get( $key ) {
    return $this->_items[ $key ];
  }
}

$c = new Configuration();
echo( $c->get( 'imgpath' )."\n" );
?>
 


如果这个对象的使用者都要直接访问项阵列,访问将被拒绝,因为该阵列被标记为 private。幸运的是,使用者发现 get() 方法可以提供广受欢迎的读取权限。

为了说明如何使用 protected 权限,我需要另一个类,该类必须继承自 Configuration 类。我把那个类称为 DBConfiguration,并假定该类将从数据库中读取配置值。此设置如下所示。


清单 4. access3.php

<?php
class Configuration
{
  protected $_items = array();

  public function __construct() {
    $this->load();
  }
  protected function load() { }
  public function get( $key ) {
    return $this->_items[ $key ];
  }
}

class DBConfiguration extends Configuration
{
  protected function load() {
    $this->_items[ 'imgpath' ] = 'images';
  }
}

$c = new DBConfiguration();
echo( $c->get( 'imgpath' )."\n" );
?>
 


这张清单显示了 protected 关键字的正确用法。基类定义了名为 load() 的方法。此类的子类将覆盖 load() 方法把数据添加到 items 表中。load() 方法对类及其子类是内部方法,因此该方法对所有外部使用者都不可见。如果关键字都是 private 的,则 load() 方法不能被覆盖。

我并不十分喜欢此设计,但是,由于必须让 DBConfiguration 类能够访问项阵列而选用了此设计。我希望继续由 Configuration 类来完全维护项阵列,以便在添加其他子类后,那些类将不需要知道如何维护项阵列。我做了以下更改。


清单 5. access4.php5

<?php
class Configuration
{
  private $_items = array();

  public function __construct() {
    $this->load();
  }
  protected function load() { }
  protected function add( $key, $value ) {
    $this->_items[ $key ] = $value;
  }
  public function get( $key ) {
    return $this->_items[ $key ];
  }
}

class DBConfiguration extends Configuration
{
  protected function load() {
    $this->add( 'imgpath', 'images' );
  }
}

$c = new DBConfiguration();
echo( $c->get( 'imgpath' )."\n" );
?>
 

上一页  [1] [2] [3] [4] [5] 下一页

我来说两句:

1分 2分 3分 4分 5分
姓名: *


* 请各位网友遵纪守法并注意语言文明。
网站简介 | 联系方式 | 意见建议 | 版权说明
Copyright © 2007 All rights reserved
滇ICP备06006992号