【问题标题】:PHP Global array in function into class function?函数中的PHP全局数组转换为类函数?
【发布时间】:2020-05-11 17:58:53
【问题描述】:

我的班级(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"];

}
}
}

我希望在我的 content.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() 可以加载到我的 content.php 中;在我的 index.php 中,在包含 header.php、content.php 和 footer.php 之前,我加载了 Post->getPosts()。谢谢你。

【问题讨论】:

    标签: php arrays function class globals


    【解决方案1】:

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

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

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

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

    【讨论】:

      猜你喜欢
      • 2011-01-15
      • 2019-04-19
      • 2013-02-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多