在类中使用外部变量

I have a directory structure:

app
cofig
 config.php
classes
 db.class.php
index.php 

config.php:

<?php

define('DB_HOST', 'localhost'); 
define('DB_USER', 'root'); 
define('DB_PASS', ''); 
define('DB_NAME', 'db_name');  

db.class.php:

<?php 
include "config/config.php";

class DB {

private $conn;
private $results;

public function __construct() {

$this->conn = mysql_connect(DB_HOST, DB_USER, DB_PASS);//**This doesn't work**
mysql_select_db(DB_NAME, $this->conn);
}

}
?>

when I try to create an instance of the $db class in index.php, I get errors (cannot obtain DEFINED variables in class)

Pass these variables to your class as parameters, it's cleaner anyway.

class DB {
    public function __construct($host, $dbName, $user, $password) {
        $this->conn = mysql_connect($host, $user, $password);
        mysql_select_db($dbName, $this->conn);
    }
}

new DB(DB_HOST, DB_NAME, DB_USER, DB_PASS);

By the way, mysql_ functions are in the process of being deprecated.

Assuming that "cofig" in your directory structure is a typo, use:

include("../config/config.php");

Having this directory structure:

app
config
 config.php
classes
 db.class.php
index.php 

will force you to use: include('../config/config.php'); or define an absolute PATH that goes to the root and do: include(PATH.'config/config.php');.

Your include "config/config.php"; is interpreted as include('root/classes/config/config.php') which, I assume, doesn't exists.

You should anyway pass, as Samy suggested, constants to the class via constructor so that you can use the same class for multiple connection with different database variables.

And also, it is not suggested to use mysql or mysqli function anymore. Learn about PDO.

According to your directory structure include path should be '../config/config.php'. Since you are using include, it does not throw fatal error and continue code execution whther file is included or not. Here your file is not included as per the code. Try this

  <?php 
include "../config/config.php";

class DB {

    private $conn;
    private $results;

    public function __construct() {

        $this->conn = mysql_connect(DB_HOST, DB_USER, DB_PASS);//**This doesn't work**
        mysql_select_db(DB_NAME, $this->conn);
     }

 }
?>