create instance of two classes together
Im trying to display two list: one for categories and brand but only the categories are being displayed. And when I remove the code for categories, the brands are being displayed. Is it because it is not possible to create instances of two classes in the same php page? In index.php:
<?php
$obj = new CategoryList();
if (method_exists($obj, 'init'))
{
$obj->init();
}
for($i = 0;$i< count($obj->mCategory); $i++)
{
echo "&l开发者_C百科t;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>";
}
?>
Here's the code for the classes:
$mSelectedCategory = (int)$_GET['category_id']; } public function init() { $this->mCategory = Catalog::GetCategory(); } } ?><?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();
}
}
?>
Maybe this might help:
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);
}
}
in DatabaseHandler class:
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;
}
You can instantiate dozens/hundreds/X of objects of any kind within the same php instance.
Use a debugger or add more debug (echo) code to find the error.
e.g. using this dummy implementation of the two classes
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'),
);
}
}
your code prints
<a href=''>Cat A<br/></a><a href=''>Cat B<br/></a><a href=''>Brand A<br/></a><a href=''>Brand B<br/></a>
without any problem.
No, you can create any number of instances even for the same class. Make sure that your both classes are included in your script independently of each other.
精彩评论