ganjan ganjan - 1 month ago 4
PHP Question

__autoload($class) not working? class not found error

I am following some examples in the

PRO PHP AND JQUERY
book, but for some reason the examples doesn't work. Even the examples that I downloaded from the books site doesn't work. Not sure whats wrong, because I have done exactly as in the book..

/public/Index.php

include_once '../sys/core/init.inc.php';
$cal = new Calendar($dbo, "2010-01-01 12:00:00"); //ERROR Class 'Calendar' not found


/sys/core/init.inc.php

function __autoload($class)
{
$filename = "../sys/class/class." . $class . ".inc.php";
if ( file_exists($filename) )
{
include_once $filename;
}
}


/sys/class/class.calendar.inc.php

class Calendar extends DB_Connect
{
private $_useDate;
private $_m;
private $_y;
private $_daysInMonth;
private $_startDay;

/**
* Create a database containg relevant info
*
* @param object $dbo a database object
* @param string $useDate the date to build calender
*/

public function __construct($dbo=NULL, $useDate=NULL)
{
/*
* Call the parent constructor to check db object
*/
parent::__construct($dbo);
}


}


This is very annoying since every chapter in the books builds on this simple foundation. My guess is that
__autoload()
is the problem, but I have no idea..

Answer

The filepaths do not point to the right spots.

A better idea would be something like this in Index.php...

define('DOCROOT', dirname(__FILE__));

...and then modify your __autoload() like so...

function __autoload($class)
{
    $filename = DOCROOT . "/sys/class/class." . strtolower($class) . ".inc.php";
    if ( file_exists($filename) )
    {
        include_once $filename;
    }
}

You should strotlower() the filename before including it, as your class is Calendar but your filename has calendar.