Tural Ali
Tural Ali

Reputation: 23240

Autoload class issue

Trying to autoload classes from <root>/incl/classes folder.

The problem is, when I call some class for ex. ip like that

        $ip= new ip();
        $ip=$ip->get();

PHP gives error message Notice: Undefined variable: path . But in fact file already exists

enter image description here

I'm declaring all various paths at the top of page.

define("ds", DIRECTORY_SEPARATOR);
$path = array();
$path['root'] = $_SERVER['DOCUMENT_ROOT'];
$path['common'] = $path['root'] . ds . "common";
$path['design'] = $path['root'] . ds . "design";
$path['contents'] = $path['root'] . ds . "contents";
$path['content_images'] = $path['root'] . ds . "content" . ds . "images";
$path['design_images'] = $path['root'] . ds . "design" . ds . "images";
$path['blocks'] = $path['contents'] . ds . "blocks";
$path['includes'] = $path['root'] . ds . "incl";
$path['pages'] = $path['contents'] . ds . "pages";
$path['classes'] = $path['includes'] . ds . "classes";

$files = glob("common" . ds . "*.php");
array_unshift($files, $path['common'] . ds . "settings.php", $path['common'] . ds . "db.php");
foreach ($files as $filename)
    require_once $filename;

//Auto loading classes
function __autoload($class_name) {
    if (file_exists($path['classes'] . ds . $class_name . '.php')) {
        require_once($path['classes']. ds . $class_name . '.php');
    } else {
        die($path['classes'] . ds . $class_name . '.php');
    }
}

For testing purposes added die($path['classes'] . ds . $class_name . '.php'); line. It outputs \ip.php. I wonder, why it doesn't echo $path['classes'] even if I declared it before ?

Upvotes: 0

Views: 319

Answers (1)

mario
mario

Reputation: 145472

It's a scoping issue. Your $path variable doesn't exist in your autoload function. It is a global variable, and you need to explicitly "invite" it:

function __autoload($class_name) {
    global $path;

You should actually have gotten a notice about this.

Upvotes: 3

Related Questions