Search code examples
phpclassrequiremailgun

PHP does a subsequently required file have access to previous requirements?


If I require a file, say a Composer autoload script, can a file I subsequently require, access the 'contents' of that file? I've never had a problem with this before but I seem to be running up against a brick wall.

Loading script:

//load required class files
require "../server/frameworks/vendor/autoload.php";
//alias
use Mailgun\Mailgun;
//get config
require "../server/sitetools/config.php";

config.php

class sitetools{
    function __construct(){
        //Instantiate Mailgun
        $this->mg = new Mailgun("API_KEY");
        $this->domain = "domail.tld";
    }
}

I then get an error from my sitetools class when I try to instantiate it: Class 'Mailgun\Mailgun' not found


Solution

  • You need to add the namespace to config.php, not the loading script (if you don't use it there...).

    config.php

    use Mailgun\Mailgun;
    
    class sitetools {
        function __construct(){
            //Instantiate Mailgun
            $this->mg = new Mailgun("API_KEY");
            $this->domain = "domail.tld";
        }
    }
    

    And by using the same filename for your script and your class, you should be able to use the composer autoloader for your own classes as well (it might require a bit more configuration...).