Search code examples
phpcodeignitercodeigniter-3static-variables

static variable called in function giving error undefined codeigniter php


I have defined static variable in controller but when I use that variable in functions it is giving undefined variable error.

Controller

<?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 gets printed properly with jwt but I am getting an error

Undefined variable: secure_key

I tried different methods to define $secure_key as

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

I tried to define $secure_key in constructor also as $secure_key = "aXXXXXXXc;

but no use. Why so? Please help. I am using codeigniter 3


Solution

  • Recommended Method (Based on Security)

    Define variables in config.php and access it. This will work like Global Variable

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

    Access it like this

    $this->$secure_key
    

    As per Comment by cd001

    self::$secure_key 
    

    If function

    $this->function_name();