如何将数据存储在类函数中的变量中,然后在外部进行访问

时间:2018-12-29 13:01:40

标签: php function oop php-5.3

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

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

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">

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

2 个答案:

答案 0 :(得分:1)

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

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

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

答案 1 :(得分:0)

如果这4个静态变量是对象属性,则需要在类中定义它们:

class Tip Extends Connection
{
    public $title;
    public $status;
    public $featured_image;
    public $excerpt;

... public function show()...

您的show()方法不返回任何内容,因此我的假设是您只想调用一次show方法,该方法将填充公共属性,然后在其他一些地方显示这些属性的值。

如果将属性定义为公共属性,则可以直接在对象上访问它们:

$tipObject = new Tip();
$tipObject ->show();
echo $tipObject ->title; // no dollar sign after $this->

此外,如果将它们定义为静态的(如下面的示例所示),则可以在不使用类名创建对象的情况下访问它们:

class Tip Extends Connection
{
    public static $title;
    public static $status;
    public static $featured_image;
    public static $excerpt;

    ...
}

echo Tip::$title; // with the dollar sign after ::
相关问题