我在application / helpers /中创建了一个函数,从ci访问时工作正常。现在我想从外部ci调用相同的函数,即从核心PHP文件调用。但我无法这样做。
以下是尝试的方法。
在ci之外创建了一个test.php,下面是代码:
<?php
$filepath = dirname(__FILE__);
ob_start();
require_once($filepath.'/ci/index.php');
ob_get_clean();
return $CI;
?>
在另一个核心PHP文件test2.php中,下面是代码:
$CI = require_once('test.php');
echo $CI->config->item('base_url');
some_helper_function($param1, $param2);
错误信息:
Fatal error: Call to a member function item() on a non-object in <path>/Utf8.php on line 47
文件夹结构:
test.php
test2.php
ci/application/helpers/test_helper.php (contains some_helper_function())
有什么建议?
创建一个文件并将以下代码放入其中。
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
if ( ! function_exists('test_function'))
{
function test_function()
{
//your functionality//
}
}
将此保存到application / helpers /。将其保存为“test_helper.php”
第一行是为了确保文件不能包含在Code Igniter外部并从中运行。
然后在你的控制器或模型中
$this->load->helper('test_helper');
您可以使用该帮助页面中的任何功能。
其他
你的项目名\程序\设置\ autoload.php
$autoload['helper'] = array('test_helper');
这样您就可以在任何控制器或模型中使用该辅助函数。不像之前所说的那样在每个控制器或模型中初始化。