You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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 CodeIgniter system directory, not the root filesystem.
  • Loading only Controller.php doesn't trigger CodeIgniter's core initialization workflow. The CI_Controller::get_instance() method returns null until 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 BASEPATH and APPPATH to avoid relative path confusion.
  • The load->helper() method doesn't return a value, so var_dump($CI->load->helper('url')) will always show null—this is expected behavior. Test with a helper function like base_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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 08:45:55