2016-04-25 29 views
3

我想從一個common_helper.php文件調用核心php文件中的函數,該文件位於codeigniter的application/helpers文件夾中。在助手文件中被接收到的函數也用於成員控制器中。所以在codeigniter網站這是工作。但不是在PHP核心是outside.Please幫我如何從常用助手外部應用程序文件夾調用函數?

文件結構:

項目/ test.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; 
} 

test.php的

include_once "../application/helpers/common_helper.php"; 
$reg = reg_code(); 
echo "Reg Code :".$reg; 
+0

首先檢查您的文件'common_helper.php'是否已加載... –

+0

是它的加載因爲我有被調用的電子郵件功能。即使在這些功能回聲。但我想fordb訪問有一些我不知道的。@ Praveen – piya

回答

0

您使用$ CI = & get_instance();在這個調用之後,在你的幫助函數 中,在那個$ CI變量中有主要的框架類對象,這就是爲什麼當你在控制器中使用它時一切正常。但是當你在覈心php文件中使用它時,你不會初始化框架類,所以方法調用get_instance()失敗並且沒有任何工作。

+0

那麼解決方案是什麼? @ Denis Alimov。 – piya

+0

如果你仍然想使用助手,你應該初始化所需的框架類。如何做到這一點取決於你的codeigniter版本,但通常這是一項艱鉅的任務。你可以看看它是如何在index.php中完成的。 @piya –

0

我的自定義助手 - (custom_helper.php)

<?php 

if(!function_exists('p')) 
{ 
    function p($arr) 
    { 
     echo '<pre>'; 
     print_r($arr); 
     echo '</pre>'; 
    die; 
    } 
} 

?> 

然後我創建我sample.php文件中項目的根目錄

sample.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'); 
相關問題