我的班級(帖子.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()。謝謝你。
1 回答

萬千封印
TA貢獻1891條經驗 獲得超3個贊
這可以替換為具有靜態變量的函數:
<?php
function get_all_posts() {
static $posts;
if(is_null($posts))
$posts = (new MYSQL) -> getAllPosts();
return $posts;
}
但是您的問題是,在調用 之前,您需要先調用全局分配。請注意,如果您尚未創建 Post 實例,則此函數必須是靜態的(或對象必須是單例)。如果這成為靜態方法,則get_posts方法也必須變為靜態方法。Post::all_posts()
壓縮到一個函數中可以使包裝器更簡單。但是,您確實失去了類自動加載的好處。
- 1 回答
- 0 關注
- 88 瀏覽
添加回答
舉報
0/150
提交
取消