KyleJR Posted January 10, 2017 Share Posted January 10, 2017 (edited) It seems that I'm struggling with an issue trying to pass a variable to the class file, but tells me the $db is undefined when I call the User::getUser(). Any ideas how can I achieve passing the $db that is defined in the bootstrap.inc.php and then using it in the auto loaded class file User? In my bootstrap.inc.php file which it's included in the index.php file. <?php # Autoload the classes spl_autoload_register("autoload"); # Autoload Composer Libraries require_once('composer/autoload.php'); # Set up the database connection $db = \ParagonIE\EasyDB\Factory::create( 'mysql:host='.DB_HOST.';dbname='.DB_NAME, DB_USERNAME, DB_PASSWORD ); # Function to load the required classes files function autoload($class_name) { # Load classes... if(file_exists(CLASS_PATH.DS.$class_name.'.class.php')) { require CLASS_PATH.DS.$class_name.'.class.php'; return; } } And then in my User.class.php file, I called the getUser function, and then it said undefined variable $db. <?php class User { public static function getUser() { $userData = $db->row("SELECT * FROM users WHERE id = ?", 1); return $userData; } } I appreciate any solutions! Edited January 10, 2017 by KyleJR Quote Link to comment https://forums.phpfreaks.com/topic/302903-passing-variables-into-auto-loaded-class-files/ Share on other sites More sharing options...
Solution requinix Posted January 10, 2017 Solution Share Posted January 10, 2017 Variables defined outside functions are not available inside functions. Pass $db as an argument to the method. Quote Link to comment https://forums.phpfreaks.com/topic/302903-passing-variables-into-auto-loaded-class-files/#findComment-1541248 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.