我正在尝试从codeigniter的应用程序/助手文件夹中的common_helper.php文件中调用核心PHP文件中的函数。在辅助文件中写入的函数也用于成员控制器。所以在代码点火器站点中,这是有效的。但不是在外面的核心 php 中。请帮助我
文件结构:
项目/测试.php
应用程序/控制器/成员
应用程序/助手/common_helper.php
这是我的common_helper.php
function reg_code()
{
$CI =& get_instance();
echo "in registration_code";
$registration_code = get_reg_code();
return $registration_code;
}
function check_code($registration_code)
{
$CI =& get_instance();
$sql = "SELECT * FROM membership WHERE reg_code = '$registration_code'";
$query = $CI->db->query($sql);
if($query->num_rows() > 0){
return FALSE;
}else{
return TRUE;
}
}
function get_reg_code()
{
$CI =& get_instance();
$CI->load->helper('string');
$alha_result = random_string('alpha',1);
$numeric_result = random_string('numeric',3);
$reg_code = $alha_result.$numeric_result;
$reg_code = strtoupper($reg_code);
//check if code exists
if(check_code($reg_code)){
return $reg_code;
}else{
get_reg_code();
}
return $reg_code;
}
测试.php
include_once "../application/helpers/common_helper.php";
$reg = reg_code();
echo "Reg Code :".$reg;
在辅助函数中使用$CI = & get_instance();在此调用之后,该$CI变量中有主框架类对象,这就是为什么当您在控制器中使用它时,一切都可以正常工作。但是当你在核心php文件中使用它时,你不会初始化框架类,所以方法调用get_instance()失败并且没有任何效果。
我的自定义帮助程序 -- (custom_helper.php)
<?php
if(!function_exists('p'))
{
function p($arr)
{
echo '<pre>';
print_r($arr);
echo '</pre>';
die;
}
}
?>
然后我在项目根目录中创建了 i sample.php 文件
样品.php --
<?php
include('./application/helpers/custom_helper.php');
$arr = array('1','2','3','4');
p($arr);
?>
输出--
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
)
请使用这种方式,它将 100% 工作,并且不要在帮助程序文件中使用以下行,使用我们可以在应用程序文件夹之外访问帮助程序方法。
if ( ! defined('BASEPATH')) exit('No direct script access allowed');