【问题标题】:Codeigniter: Set 'global variable'Codeigniter:设置“全局变量”
【发布时间】:2013-11-19 19:40:36
【问题描述】:

如果我想设置一个我的整个控制器都可以访问的变量,我该怎么做?

现在,在我设置的每个功能中

$id = $this->session->userdata('id');

我希望能够从任何函数访问 $id,而无需为每个控制器定义它。 :)

如果有更好的方法,我会全力以赴!我是菜鸟!

【问题讨论】:

    标签: session codeigniter variables


    【解决方案1】:

    要详细说明Koo5's response,您需要执行以下操作:

    class yourController extends Controller {
    
        // this is a property, accessible from any function in this class
        public $id = null;
    
        // this is the constructor (mentioned by Koo5)
        function __construct() {
            // this is how you reference $id within the class
            $this->id = $this->session->userdata('id');
        }
    
        function getID() {
            // returning the $id property
            return $this->id;
        }
    
    }
    

    有关 PHP propertiesconstructors 的更多信息,请参阅手册。希望对您有所帮助!

    【讨论】:

    • 你又救了我,科林。谢谢!
    【解决方案2】:

    如果 global 是指单个控制器的范围,则上述答案是正确的。如果您想从多个控制器访问变量,我建议您定义一个 BaseController 类,然后扩展您的普通控制器以从该 BaseController 继承:

    class yourController extends BaseController {}
    

    我一直将它用于全局变量和方法。

    【讨论】:

      【解决方案3】:

      仅在构造函数中定义该行

      【讨论】:

      • 我得到“未定义的变量”。能否提供更多信息?
      【解决方案4】:

      您也可以在控制器中使用此方法

      function __construct() {
          // this is how you reference $id within the class
          DEFINE("userId",$this->session->userdata('id'));
      }
      

      并称之为:

      function getID() {
          // returning the $id property
          return userId;
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-07-18
        • 2020-07-23
        相关资源
        最近更新 更多