Backend Development

Error with class array

Submitted by bVnDBsapg, , Thread ID: 97384

Thread Closed
01-08-2018, 11:50 PM
#1
A while ago I was trying to learn PHP OOP by using classes to make a simple forum system. I have a function that will return an array of Post objects. The problem I'm having is I tried to loop over them and call a function, but for some reason PHP is treating them like a number. I have it check if the object is an instanceof Post yet it doesn't work.

Heres a snippet of my code:

PHP Code:
$posts Database::LoadPosts(isset($_GET['page']) ? intval($_GET['page']) : 1);

  for(
$i=0$i sizeof($posts); $i++){
    
$post $posts[$i];
    if(
$post instanceof Post) {
      echo 
$post->GetHTML();
    }
  } 

RE: Error with class array

#2
I believe your error will be within the LoadPosts function. I believe you can only store stdObject and instantiated objects within an array.

I quick tip, I would be using a foreach loop to loop through the objects and not an iterator like you've got, i.e.

Code:
$posts = array([objects]);

foreach($posts as $key=>$post_object){

       $post_object->object_function();
       $posts[$key][change something in the original array] = [];

}

Users browsing this thread: 1 Guest(s)