一起创建两个类的实例

时间:2009-12-31 11:05:34

标签: php oop class pdo

我试图显示两个列表:一个用于类别和品牌,但只显示类别。当我删除类别代码时,正在展示品牌。是因为不可能在同一个php页面中创建两个类的实例吗? 在index.php中:

 <?php 
 $obj = new CategoryList();
 if (method_exists($obj, 'init'))
 {  

     $obj->init();
 }
for($i = 0;$i< count($obj->mCategory); $i++)
{
    echo "<a href=''>";
    echo $obj->mCategory[$i]['name']. "<br/>";
    echo "</a>"; 
} 

$obj2 = new BrandList();
if (method_exists($obj2, 'init'))
{
  $obj2->init();
}
for($i = 0;$i< count($obj2->mBrand);$i++)
{
   echo "<a href=''>";
   echo $obj2->mBrand[$i]['name']. "<br/>";
   echo "</a>"; 
    }
 ?>

以下是类的代码:

$ mSelectedCategory =(int)$ _ GET ['category_id'];         }         公共函数init()         {             $ this-&gt; mCategory = Catalog :: GetCategory();         }     }     ?&GT;
<?php

class BrandList
{
    public $mSelectedBrand = 0;
    public $mBrand;


    public function __construct()
    {
        if (isset ($_GET['brand_id']))
            $this->$mSelectedBrand = (int)$_GET['brand_id'];
    }


    public function init()
    {
        $this->mBrand = Catalog::GetBrand();

    }


}

?>

也许这可能会有所帮助:

class Catalog
{
    //get id and name of category
    public static function GetCategory()
    {
        $sql = 'CALL catalog_get_category_list()';
        return DatabaseHandler::GetAll($sql);

    }

public static function GetBrand()
{
    $sql = 'CALL catalog_get_brands_list()';
    return DatabaseHandler::GetAll($sql);

}

}
在DatabaseHandler类中:

 public static function GetAll($sqlQuery, $params = null, $fetchStyle = PDO::FETCH_ASSOC)
        {
            $result = null;
            try
            {
                $database_handler = self::GetHandler();
                $statement_handler = $database_handler->prepare($sqlQuery);
                $statement_handler->execute($params);
                $result = $statement_handler->fetchAll($fetchStyle);



            }
            catch(PDOException $e)
            {
                self::Close();
                trigger_error($e->getMessage(), E_USER_ERROR);

            }
            return $result;
        }

2 个答案:

答案 0 :(得分:1)

您可以在同一个php实例中实例化几十个/几百个X对象 使用调试器或添加更多调试(回声)代码来查找错误。

e.g。使用这两个类的虚拟实现

class CategoryList {
  public $mCategory=null;
  public function init() {
    $this->mCategory = array(
      array('name'=>'Cat A'),
      array('name'=>'Cat B'),
    );
  }
}

class BrandList {
  public $mBrand=null;
  public function init() {
    $this->mBrand = array(
      array('name'=>'Brand A'),
      array('name'=>'Brand B'),
    );
  }
}

您的代码打印

<a href=''>Cat A<br/></a><a href=''>Cat B<br/></a><a href=''>Brand A<br/></a><a href=''>Brand B<br/></a>

没有任何问题。

答案 1 :(得分:1)

不,即使是同一个班级,您也可以创建任意数量的实例。确保您的两个类彼此独立地包含在脚本中。

相关问题