php - 如何将数据存储在类函数的变量中,然后在外部访问它
问题描述
我正在尝试创建一个页面,它将从数据库中加载值并显示它。但是,我使用了类而不是普通函数。
以下是我正在执行的中间代码
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">
它没有显示错误,也没有显示数据。只是想知道这是我的代码出错了。
解决方案
$title
不在你的方法范围内show()
。
只需global $title
在方法内部添加即可。
但是我建议将变量声明为类的属性Tip
并使用$tip->title
;
推荐阅读
- windows - mouse_event / PostMessage 按键消息 - 与 GetKeyState() 不一致
- csv - JMeter 读取/写入 CSV 数据集配置
- javascript - 模拟时钟无法读取 null 的属性
- java - 为什么不推荐使用 IOUtils.close?
- python - 从变量传递参数 - Python
- python - 如何异步运行同一类的多个实例?
- html - 如何在 .cshtml 中获得这样的布局
- java - 如何从 Java 中的错误消息中去除 Oracle 错误代码?
- firebase - 获取“firebase.functions(app)”参数需要一个 FirebaseApp 实例或在 React-Native Firebase 中未定义
- typescript - TS2322:类型 'Foo | Bar' 不可分配给类型 'Foo & Bar'