2

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

1
  • 1
    $token = JWT::encode($postdata, $secure_key); ... $postdata appears to be undefined and $secure_key is a static class variable (so self::$secure_key) ? Commented Oct 18, 2017 at 9:51

2 Answers 2

4

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();
Sign up to request clarification or add additional context in comments.

4 Comments

$secure_key is static ... so self::$secure_key rather than $this->secure_key
yeah any value which is used in the project globally, must be defined in config.php and should be loaded from config inside the code
Thanks a lo it works. This means whenever I define static variable in codeigniter I need to write self::$secure_key or class_name::$variale_name to use it right.
But @Abdulla if we define in config still we can change its value as given in answer as item and set_item. What if I dont want to change value of that variable, then static would be much prefarable?
3

Since $secure_key is declared as static inside your class. So it can be accessed using self or className as

self::$secure_key

or

Quiz::$secure_key

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.