为什么我的班级找不到其他班级的变量

我是 OOP 的新手,为什么我在其他文件中的类在我包含的其他类中找不到变量..?我尝试发送变量 $db 但它给了我错误。


第一课


<?php

//making Database connection

class DBconnection

{

    public function __construct()

    {

        DEFINE("DB_USER", "root"); // username database

        DEFINE("DB_PASS", ""); // password database

        try {

            $db = new PDO("mysql:host=localhost;dbname=php_opdracht2", DB_USER, DB_PASS); //host & database name

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

            echo "Connected successfully";


        } catch (PDOException $e) {

            echo $e->getMessage();

        }

    }

}

//running the class DBconnection

$obj = new DBconnection();

第二类(另一个 .php 文件)


<?php

//getting the database connection

require_once('DBconnection.php');


//getting the data from the database

class Controller

{

    public function processing()

    {

        try {

            $query   = "SELECT * FROM information";

            $sth     = $db->query($query); //why does it not find $db..

        } catch (PDOException $e) {

            echo $e->getMessage();

        }

    }

}

$obj3 = new Controller();

$obj3->processing();


红颜莎娜
浏览 130回答 1
1回答

慕村225694

在您的 DBconnection 类中,声明一个公共变量来保存数据库连接<?php//making Database connectionclass DBconnection {&nbsp; &nbsp; public $db;&nbsp; &nbsp; public function __construct() {&nbsp; &nbsp; &nbsp; &nbsp; DEFINE("DB_USER", "root"); // username database&nbsp; &nbsp; &nbsp; &nbsp; DEFINE("DB_PASS", ""); // password database&nbsp; &nbsp; &nbsp; &nbsp; try {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $this->db = new PDO("mysql:host=localhost;dbname=php_opdracht2", DB_USER, DB_PASS); //host & database name&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; echo "Connected successfully";&nbsp; &nbsp; &nbsp; &nbsp; } catch (PDOException $e) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; echo $e->getMessage();&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}然后在另一个类中,访问它如下<?php//getting the database connectionrequire_once('DBconnection.php');//getting the data from the databaseclass Controller {&nbsp; &nbsp; public function processing() {&nbsp; &nbsp; &nbsp; &nbsp; try {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $connection = new DBconnection(); #call db class&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $query = "SELECT * FROM information";&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $sth = $connection->db->query($query); //access the db variable created in db class&nbsp; &nbsp; &nbsp; &nbsp; } catch (PDOException $e) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; echo $e->getMessage();&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP