简体   繁体   中英

PHP Array of Objects :: Cannot use object of type <MyObject> as array

I have a class represents a table in database I want to fill the table into array of objectsas following:

$subCat = array();
$count=0;
while($line = mysql_fetch_array($result, MYSQL_ASSOC)) {
    $subCatName = $line["sub_cat_name"];
    $subCatShortDescription = $line["short_description"];
    $subCatLongDescription = $line["long_description"];
    $subCat = new SubCat($countryId, $catName, $subCatShortDescription, $subCatLongDescription);
    $subCat[$count++] = $subCat;
}

I get the following error:

Fatal error: Cannot use object of type SubCat as array in C:\AppServ\www\MyWebSite\classes\SubCat.php on line 34

Thanks

You're using your object as an array:

$subCat = array():
// ... code
$subCat = new SubCat($countryId, $catName, $subCatShortDescription, $subCatLongDescription);
$subCat[$count++] = $subCat;

When you assign the new object to $subCat it's no longer an array, so $subCat[$index] .

Instead use something like:

$subCat = array();
// ... code
$subCat[$count++] = new SubCat($countryId, $catName, $subCatShortDescription, $subCatLongDescription);                  

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM