3

我有以下代码:

(一步步)

  1. 放入counter.txt_APPPATH . 'logs/counter.txt'
  2. counter_helper.php设置在APPPATH . 'helpers/counter_helper.php';
  3. 在文件中自动加载新创建的帮助APPPATH . 'config/autoload.php'程序;
  4. MY_Controller.php进入_APPPATH . 'core/MY_Controller.php'
  5. 任何控制器都应该扩展MY_Controller而不是CI_Controller;
  6. 在页面上回显它:<?php echo $this->count_visitor;?>

助手:

<?php defined('BASEPATH') OR exit('No direct script access allowed.');

if ( ! function_exists('count_visitor')) {
    function count_visitor()
    {
        $filecounter=(APPPATH . 'logs/counter.txt');
        $kunjungan=file($filecounter);
        $kunjungan[0]++;
        $file=fopen($filecounter, 'w');
        fputs($file, $kunjungan[0]);
        fclose($file);
        return $kunjungan[0];
    }
}

核心 :

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class MY_Controller extends CI_Controller
 {
  public $count_visitor;
  public function __construct()
   {
     parent::__construct();
      $this->count_visitor = count_visitor();
   }   
 }
/* End of file MY_Controller.php */
/* Location: ./application/core/MY_Controller.php */

控制器:

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
 class Home extends MY_Controller {
 public function index() {
 $data=array('isi'      =>'home/index_home');
$this->load->view('layout/wrapper',$data); 
 }
}

风景 :

<?php echo $this->count_visitor;?>

代码返回如下错误: 在此处输入图像描述

4

2 回答 2

2

当我加载助手时,我让它工作正常$this->load->helper('counter');

应用程序 > 核心 > MY_Controller.php

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class MY_Controller extends CI_Controller
{
    public $count_visitor;

    public function __construct()
    {
        parent::__construct();
        $this->load->helper('counter');
        $this->count_visitor = count_visitor();
    }   
}
于 2015-07-28T22:41:53.810 回答
0

是的,必须加载帮助程序:

$this->load->helper('counter');

或者

配置/自动加载.php: $autoload['helper'] = array('counter');

于 2018-04-28T19:42:58.903 回答