Shell调用非CI目录PHP文件时,CodeIgniter get_instance函数报错求助
Fixing "Trying to get property 'load' of non-object" when accessing CodeIgniter instance from external PHP
Let's break down why your code is throwing that error and how to fix it properly:
Why your current approach fails
- You set
BASEPATH = "/"which is incorrect—this constant should point directly to your CodeIgnitersystemdirectory, not the root filesystem. - Loading only
Controller.phpdoesn't trigger CodeIgniter's core initialization workflow. TheCI_Controller::get_instance()method returnsnulluntil the framework has fully booted up, which is why you're getting the "non-object" error when trying to access$CI->load.
Correct solution: Bootstrap the full CodeIgniter framework
To get a valid CI instance from an external file, you need to initialize the entire framework instead of loading isolated files. Here's a working example:
<?php // Define the absolute paths to your CodeIgniter installation define('BASEPATH', '/full/path/to/your/ci-application/system/'); define('APPPATH', '/full/path/to/your/ci-application/application/'); // Load CodeIgniter's core bootstrap file to initialize the framework require BASEPATH . 'core/CodeIgniter.php'; // Now you can safely retrieve the CI instance $CI =& get_instance(); // Load the URL helper (note: this method returns void, so var_dump will show null) $CI->load->helper('url'); // Verify the helper works by using one of its functions var_dump(base_url()); // This should output your app's configured base URL
Important notes
- Always use absolute paths for
BASEPATHandAPPPATHto avoid relative path confusion. - The
load->helper()method doesn't return a value, sovar_dump($CI->load->helper('url'))will always shownull—this is expected behavior. Test with a helper function likebase_url()instead to confirm it's loaded. - If you only need to run specific CI logic, consider creating a controller method and invoking it via CLI or HTTP request instead—it's the more "CodeIgniter-native" way to handle external calls.
内容的提问来源于stack exchange,提问作者Stefano Maglione
相关产品推荐
相关产品推荐

