PHP 全局数组在函数中变成类函数?



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"];
}
}
}

我希望在我的内容中.php我可以调用 all_posts(( 函数来获取数组并像这样打印:

<div class="posts">
<?php foreach(all_posts() AS $post) : ?>
<h1><?php echo $post["title"]</h1>
<p><?php echo $post["content]; ?></p>
<?php endforeach; ?>
</div>

我希望函数 all_posts(( 可以在我的内容中加载.php;在我的索引.php中,在包含页眉.php,内容.php和页脚之前.php我加载Post->getPosts((。谢谢。

这可以替换为带有静态变量的函数:

<?php
function get_all_posts() {
static $posts;    
if(is_null($posts))
$posts = (new MYSQL) -> getAllPosts();
return $posts;
}

但是您的问题是您需要调用Post::all_posts()之前调用全局赋值。 请注意,如果您尚未创建 Post 实例,则此函数必须是静态的(或对象为单一实例(。 如果这成为静态方法,则get_posts方法也必须变为静态方法。

压缩成一个函数可以使包装器更简单。 但是,您确实失去了类自动加载的好处。

最新更新