【问题标题】:static variable called in function giving error undefined codeigniter php函数中调用的静态变量给出错误未定义的codeigniter php
【发布时间】:2018-03-30 03:33:21
【问题描述】:

我已经在控制器中定义了静态变量,但是当我在函数中使用该变量时,它会给出未定义的变量错误。

控制器

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

class Quiz extends Admin_Controller {

    private static $secure_key = "aXXXXXXXXc";

    public function __construct()
    {
        parent::__construct();
    }

    public function edit($id)
    {
        try
        {
            $token = JWT::encode($postdata, $secure_key);
            echo "<pre>";print_r($token);exit; 
        }
        catch(Exception $e){
            $this->data['error'] = $e->getMessage();
            redirect('/','refresh');
       }
    }
}

$token 使用 jwt 正确打印,但出现错误

Undefined variable: secure_key

我尝试了不同的方法将$secure_key定义为

public static $secure_key = "aXXXXXXXc;
static $secure_key = "aXXXXXXXc;

我尝试在构造函数中将$secure_key 定义为 $secure_key = "aXXXXXXXc;

但没用。为什么这样?请帮忙。我正在使用 codeigniter 3

【问题讨论】:

  • $token = JWT::encode($postdata, $secure_key); ... $postdata 似乎未定义,$secure_key 是一个静态类变量(所以self::$secure_key)?

标签: php codeigniter codeigniter-3 static-variables


【解决方案1】:

推荐方法(基于安全性

config.php 中定义变量并访问它。这将像 全局变量

一样工作
$config['secure_key'] = 'myKey';
$this->config->item('secure_key'); # get
$this->config->set_item('secure_key', 'NewKey'); # set

像这样访问它

$this->$secure_key

根据Comment by cd001

self::$secure_key 

如果函数

$this->function_name();

【讨论】:

  • $secure_key 是静态的...所以self::$secure_key 而不是$this-&gt;secure_key
  • 是的,在项目中全局使用的任何值,都必须在config.php 中定义,并且应该从代码中的config 加载
  • 感谢它的工作原理。这意味着每当我在 codeigniter 中定义静态变量时,我都需要编写 self::$secure_keyclass_name::$variale_name 才能正确使用它。
  • 但是@Abdulla 如果我们在配置中定义仍然可以将其值更改为答案中给出的itemset_item。如果我不想更改该变量的值怎么办,那么静态会更可取?
【解决方案2】:

因为$secure_key 在你的类中被声明为static。因此可以使用selfclassName as 访问它

self::$secure_key

Quiz::$secure_key

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-08-15
    • 2011-12-06
    • 2021-09-10
    • 1970-01-01
    • 2019-08-24
    • 2016-08-17
    • 2021-11-27
    相关资源
    最近更新 更多