【发布时间】:2009-12-31 11:05:33
【问题描述】:
我试图显示两个列表:一个用于类别和品牌,但只显示类别。当我删除类别代码时,会显示品牌。是不是因为不可能在同一个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']; } 公共函数初始化() { $this->mCategory = 目录::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();
}
}
?>
也许这会有所帮助:
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;
}
【问题讨论】:
-
如果您在浏览器上进行检查,请查看 HTML 源代码以查看品牌是否正在打印。如果没有,要么你的 BrandList 对象没有被填充条目,要么有错误,可能在构造函数或 init() 函数中。
-
我浏览了 html 源代码,只打印了类别..
-
$this->$mSelectedBrand- 太多了,$this->mSelectedBrand。您是否修改了 Stackoverflow 的代码,或者这真的是一个错误? -
其实是报错。
-
$pdo 对象 GetHandler() 返回是否设置为在发生错误时引发异常?就像例如
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);。你有没有留意error.log? (如果您错过了$this->$mSelectedBrand的警告,您可能也错过了 E_USER_ERROR)。