首页 > 解决方案 > 如何将数据存储在类函数的变量中,然后在外部访问它

问题描述

我正在尝试创建一个页面,它将从数据库中加载值并显示它。但是,我使用了类而不是普通函数。

以下是我正在执行的中间代码

if($_GET['page'] == "tip" && isset($_GET['id']))
{
    static $title;
    static $status;
    static $featured_image;
    static $excerpt;

    include("config.php");

    class Tip Extends Connection
    {
        public function show()
        {
            $query = ' SELECT status, title, featured_image, excerpt from tips WHERE id = "'.$_GET['id'].'" ';
            $connection = $this->establish_connection();
            $data = $connection->query($query);
            $connection->close();

            if($data->num_rows > 0)
            {
                while($row = $data->fetch_assoc())
                {
                    $title = $row['title'];
                    $status = $row['status'];
                    $featured_image = $row['featured_image'];
                    $excerpt = $row['excerpt'];
                }
            }
            else
            {
                echo json_encode(array('status' => 'No Data Found'));
                exit();
            }
        }
    }
    $tip = new Tip();
    $tip->show();
}

上面的代码在页面加载后首先被执行,之后我试图在 HTML 输入中显示变量,如下所示。

<input type="text" autofocus id="tip_title" class="tip_title round form-control" placeholder="What's the title of your Post?" value="<?php echo $title; ?>" name="tip_title">

它没有显示错误,也没有显示数据。只是想知道这是我的代码出错了。

标签: phpfunctionoopphp-5.3

解决方案


$title不在你的方法范围内show()

只需global $title在方法内部添加即可。

但是我建议将变量声明为类的属性Tip并使用$tip->title;


推荐阅读