【问题标题】:Variable in php class which can be used in all its functionsphp 类中的变量,可以在其所有函数中使用
【发布时间】:2012-06-09 18:01:17
【问题描述】:

我想在一个 php 类中声明一个变量,它可以在它的所有函数中使用。我正在使用 codeigniter 框架,并且必须在每个函数中传递 base_url 等数据。我还需要一个变量中的所有这些数据。例如$data['base_url']=base_url()$data['title']="My_Site_title" 等,然后只发送一个变量 $data(这在 codeigniter 中很常见)。

根据this 的问题,我将代码修改为:

class Search extends CI_Controller {

function Search() {
    parent::__construct();
    $this->load->model('student_model');

    $this->load->helper('form');
    $this->load->helper('url');
    $this->output->enable_profiler(TRUE);

    $this->data['base_url']=base_url();  //gives an error here
 }

 function index() {
     $this->load->view('search_view', $this->data);
 }
 }

但它仍然在标记的地方给出错误,说Undefined variable: dataFatal error: Cannot access empty property in ..\search.php on line 16

【问题讨论】:

  • 不能在没有实例的情况下使用 $data

标签: php class codeigniter scope codeigniter-2


【解决方案1】:

给你:

class Search extends CI_Controller {

protected $data = array();

function Search() {
    parent::__construct();
    $this->load->model('student_model');

    $this->load->helper('form');
    $this->load->helper('url');
    $this->output->enable_profiler(TRUE);

    $this->data['base_url']=base_url();
 }

 function index() {
     $this->load->view('search_view', $this->data);
 }
 }

更多关于 php 中的类属性:http://php.net/manual/en/language.oop5.properties.php

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-11-02
    • 2010-09-08
    • 2013-06-11
    • 2016-08-04
    • 1970-01-01
    • 2014-12-22
    • 1970-01-01
    • 2017-09-10
    相关资源
    最近更新 更多