0

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

1
  • 1
    Your code is somewhat confusing because first you define $subcat as an empty array and then you create it as some sort of object with new Subcat. Then, you try to use is as an array again. That's what PHP is complaining about. Commented Nov 28, 2014 at 23:34

1 Answer 1

2

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);                  
Sign up to request clarification or add additional context in comments.

2 Comments

actually you don't need an increment at all, just declare the array container outside on top of the while loop and just normally push the newly created object inside the loop: $subcat[] = new SubCat.
Certainly the count is not necessary. I just kept it to reply with the least changes.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.