猿问

是否可以在 php 类中使用 $conn 全局变量?

我试图在$conn课堂文章中使用变量。我创建了一个 configuration.php 文件


配置文件


try {

    $conn = new PDO('mysql:host='.$dbhost.';dbname='.$dbname, $user, $pass);

    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

} catch (PDOException $e) {

    print "Error!: " . $e->getMessage() . "<br/>";

    die();

}

我同意,这是建立数据库连接的经典方式。


我试着$conn像我说的那样在课堂上使用这个变量。


类.article.php


class Article {

    global $conn;

    public $article_id;

    function setArticle($article_id) {

        $this->article_id = $article_id;

    }


    function getArticle($article_id){

        $getArticlee = $conn->prepare("SELECT * FROM articles WHERE id = :id");

        $getArticlee->bindParam(':id', $article_id, PDO::PARAM_INT);

        $getArticlee->execute();

        return $getArticlee;

    }

}

我需要按下一个顺序执行文件(show.article.php)中的两个文件


配置文件

类.article.php

在所有这些之后,我得到一个错误,执行一个 show.article.php。当我删除


global $conn;

我没有任何错误。但是后来我没有连接到数据库。


我需要一些解决方案来将$conn变量包含在一个类中,因为这只是一个需要数据库连接的类,我将有大约 10-15 个带有 pdo 连接的类。


喵喔喔
浏览 265回答 2
2回答

LEATH

你可以放在方法global $conn里面getArticle。...function getArticle($article_id){&nbsp; global $conn; // not recommended&nbsp; $getArticle = $conn->prepare("SELECT * FROM articles WHERE id = :id");&nbsp; ...}然而,这种方法是不鼓励的,因为现在你的Article类对外部状态有隐含的依赖,并且更难推理和测试。更好的选择是将PDO对象传递给Article构造函数并将其保留为您的方法可以调用的私有属性。class Article {&nbsp; private $conn;&nbsp; public $article_id;&nbsp; ...&nbsp; function __construct(\PDO $conn) {&nbsp; &nbsp; $this->conn = $conn;&nbsp; }&nbsp; function getArticle($article_id){&nbsp; &nbsp; $getArticlee = $this->conn->prepare("SELECT * FROM articles WHERE id = :id");&nbsp; &nbsp; ...&nbsp; }}

慕田峪7331174

不可能在类中使用 $GLOBALS。你可以在你的环境中做一些改变......配置文件class Config{&nbsp;function __Construct(){&nbsp; &nbsp;try {&nbsp; &nbsp;$conn = new PDO('mysql:host='.$dbhost.';dbname='.$dbname, $user, $pass);&nbsp; &nbsp; $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);&nbsp; &nbsp;return $conn;&nbsp; &nbsp; }&nbsp;&nbsp; &nbsp;catch (PDOException $e) {&nbsp; &nbsp; print "Error!: " . $e->getMessage() . "<br/>";&nbsp; &nbsp; die();&nbsp; }}类.article.phpclass Article {protected $conn= new Config;public $article_id;function setArticle($article_id) {&nbsp; &nbsp; $this->article_id = $article_id;}&nbsp;function getArticle($article_id){&nbsp; &nbsp; $getArticlee = $this->conn->prepare("SELECT * FROM articles WHERE id = :id");&nbsp; &nbsp; $getArticlee->bindParam(':id', $article_id, PDO::PARAM_INT);&nbsp; &nbsp; $getArticlee->execute();&nbsp; &nbsp; return $getArticlee;&nbsp;}}
随时随地看视频慕课网APP
我要回答