PHP Global array in function into class function?

Tags: , , , ,



my class (posts.php):

class Posts {

private function getPosts() {

$get_post = (new MYSQL) -> getAllPosts(); // here get all posts from my db
$GLOBALS["all_posts"] = $get_posts;

function all_posts() {
// When I use the return, the page enter on one infinite bucle.. If I use echo this doesnt happen.
return $GLOBALS["all_posts"];

}
}
}

I want that in my content.php that I can call the all_posts() function to get the array and print like this:

<div class="posts">

<?php foreach(all_posts() AS $post) : ?>

<h1><?php echo $post["title"]</h1>
<p><?php echo $post["content]; ?></p>

<?php endforeach; ?>

</div>

I want that the function all_posts() can be load in my content.php; In my index.php, before include the header.php, content.php and footer.php I load the Post->getPosts(). Thanks you.

Answer

This could be replaced with a function with a static variable:

<?php

function get_all_posts() {
    static $posts;    
    if(is_null($posts))
        $posts = (new MYSQL) -> getAllPosts();

    return $posts;
}

But your problem is that you need to call the global assignment before you call Post::all_posts(). Note that this function must be static (or the object a singleton) if you haven’t created a Post instance. If this becomes a static method, your get_posts method also must become static.

Condensing into one function makes for a simpler wrapper. However you do loose the benefit of class autoloading.



Source: stackoverflow