Search code examples
phpinclude-pathrequire-once

no Mail class require_once php


I'm trying to use require_once to call Mail.php but when I create a new instance for that class and start using it I get a message that says

Fatal error: Class 'Mail' not found in D:\xampp\htdocs\proj\Mailing\mymail.php on line xx

The resumed code goes like this

<?php
     require_once 'Autoload.php';

     $smtp = Mail::factory('smtp',
          array ('host' => $host,
          'port' => $port,
          'auth' => true,
          'username' => $username,
          'password' => $password));
?>

or also

<?php
     require_once 'Mail.php';

     $mail = new Mail();
?>

Why do I get that message? I already set the include path to ".;D:\xampp\php\pear"

I edited my script and required the autoload script, which works just fine, cause it prints no error, but I still get the same message like Mail doesn't work (I edited the script above), autoload is in the same directory where my main script is.

I made a new file and called it with the full path, and then the output was

Warning: require_once(D:\xampp\php\PEAR) [function.require-once]: failed to open stream: Permission denied in D:\xampp\htdocs\proj\Mailing\pMail.php on line 2

Solution

  • When you are loading a class you don't need to require your php file if you use autoloading.

    Example:

    Class Autoload {
       private $rootDirectory;
       private $paths = array(
           "system/core",
           "system/obj",
           "system/data"
       );
    
       public function __construct() {
           $this->RootDirectory = dirname(getcwd()); // Whatever is your root
           $this->activateAutoload("autoloadClassesFromSystemFolder");
       }
    
       private function autoloadClassesFromSystemFolder($i) {
           foreach ($this->paths as $path) {
               // Please keep in mind that a class name has to be unique. 
               if (is_file($this->RootDirectory .'/'. $path .'/'. $i . ".php")) {
                   include $this->RootDirectory .'/'. $path .'/'. $i . ".php";
                   break;
               }
           }
       }
    
       public function activateAutoload($functionName) {
           spl_autoload_register(array($this, $functionName));
       }
    }
    

    The only thing you need to do to load this in php is:

    require "path/to/autoload.php";
    $autoload = new Autoload();
    

    After that you can use as many classes as you want without having to worry about class file includements.

    $mail = new Mail();
    

    More info: http://nl.php.net/autoload