我是 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();
慕村225694