Codeigniter: Using static variable - php

I am making a website in which i have to save a global variable.
I am using this person code globals_helper.php custom global variable class
But i always get static variable value null.
globals_helper.php:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
// Application specific global variables
class Globals
{
private static $authenticatedMemberId = null;
private static $initialized = false;
private static function initialize()
{
if (self::$initialized)
return;
self::$authenticatedMemberId = null;
self::$initialized = true;
}
public static function setAuthenticatedMemeberId($memberId)
{
self::initialize();
self::$authenticatedMemberId = $memberId;
}
public static function authenticatedMemeberId()
{
self::initialize();
return self::$authenticatedMemberId;
}
}
I have done all the steps like add globals_helper.php in helper folders and updated autoload file. Now I am trying to access those static variable from a custom library "Ctrl_utility" function "get_search_term" and my controllers calling get_search_term function
Ctrl_utility.php
class Ctrl_utility {
protected $CI;
public static $static_search = "";
public function __construct()
{
// Assign the CodeIgniter super-object
$this->CI =& get_instance();
}
public function get_search_term($searchTerm){
$searchTerm = $this->CI->security->xss_clean(htmlspecialchars($searchTerm));
if (isset($searchTerm) && strlen($searchTerm)>0) {
Globals::setAuthenticatedMemeberId($searchTerm);
} else {
$searchTerm = Globals::authenticatedMemeberId();
}
return $searchTerm;
}
One of my controller and they all have class ctrl_utility, get_search_term function:
class Blog_controller extends CI_Controller{
public function __construct() {
parent::__construct();
$this->load->model('blogs_model');
}
public function index(){
//Get SearchTerm Values
$searchTerm = $this->ctrl_utility->get_search_term($this->input->post('searchTerm'));
//Get Url First Parameter
$start = $this->ctrl_utility->get_url_first_parameter();
// Get Data from solr
$rows = 10;
$data = $this->blogs_model->solrData($start, $rows, $searchTerm); //give start of documents
//Pagination
$this->pagination->initialize($this->ctrl_utility->pagination_config($this->uri->segment(1), $rows, $data['found']));
//Views
$this->load->view('tabs/blogs', $data);
}
}
Am i doing something wrong?

Now when it comes to define them in CodeIgniter, there are several ways do that. I’ve listed some of them below:
Create your own file in application/libraries in which class constructor contains an array as an argument. Now create a new file in /application/config with same name as given in application/libraries and declare your global variables in it. Now to use these variables, autoload the newly created library.
Create your own file in application/core and declare the global variables in it. Than in controller you need to extend your file name instead of CI_Controller.
If the Global Variables are true constants, just add them in application/config/constants.php file and name them in all uppercase like the others are defined.
If you want to set application constants create new config file and add the variables. Now load it as $this->config->load(‘filename’); And access those variables as
$this->config->item(‘variable_name’);
Instead of creating helper create a library
Step 1: First of all, open application/libraries and create a custom
class name globals.php. It contains a constructor function which
contains an array as an argument.
<?php
class Globals {
// Pass array as an argument to constructor function
public function __construct($config = array()) {
// Create associative array from the passed array
foreach ($config as $key => $value) {
$data[$key] = $value;
}
// Make instance of CodeIgniter to use its resources
$CI = & get_instance();
// Load data into CodeIgniter
$CI->load->vars($data);
}
}
?>
Step 2: Now to make config file, open application/config and create
file as globals.php and write the code given below. This file contains
the config variable which will be passed as an array to constructor of
Globals class where its keys and values are stored in $data
<?php
// Create customized config variables
$config['web_Address']= 'https://www.example.com/blog';
$config['title']= 'CodeIgniter Global Variable';
?>
When constructor function loads, it will take the config variables
from the config file in order to use these variables anywhere.
Note: Name of the above file must be same as the class created in
libraries folder otherwise the code will not work.
Step 3: But before using these variables we have to autoload the newly
created library globals as given below.
And load library in autoload
$autoload['libraries'] = array('globals');
Now, you can use global variables in your controller
<?php
class CI_Global_Variable_Tutorial extends CI_Controller{
public function __construct() {
parent::__construct();
}
// Load view page
public function index() {
$this->load->view('show_global_variables');
}
}
?>
Views : show_global_variables.php
In view page, we can use global variables according to our need.
<?php
echo "Title of the blog post : ".$title;
echo "<a href='$web_Address'>"."Click here to go to blog page"."</a>";
?>

Related

use main file's variable inside class PHP

i have a main php file which contains the variable:
$data['username']
which returns the username string correctly.
In this main file i included a class php file with:
require_once('class.php');
they seem linked together well.
My question is: how can I use the $data['username'] value inside the class file? I'd need to do an if statement to check its value inside that class.
class.php
<?php
class myClass {
function __construct() {
if ( $data['username'] == 'johndoe'){ //$data['username'] is null here
$this->data = 'YES';
}else{
$this->data = 'NO';
}
}
}
There are many ways to do that, we could give you accurate answer if we knew how your main php file and the class look like. One way of doing it, from the top of my head:
// main.php
// Instantiate the class and set it's property
require_once('class.php');
$class = new myClass();
$class->username = $data['username'];
// Class.php
// In the class file you need to have a method
// that checks your username (might look different in your class):
class myClass {
public $username = '';
public function __construct() {}
public function check_username() {
if($this->username == 'yourvalue') {
return 'Username is correct!';
}
else {
return 'Username is invalid.';
}
}
}
// main.php
if($class->username == 'yourvalue') {
echo 'Username is correct!';
}
// or
echo $class->check_username();
If the variable is defined before the call to require_once then you could access it with the global keyword.
main.php
<?php
$data = [];
require_once('class.php');
class.php
<?php
global $data;
...
If your class.php is defining an actual class then I would recommend Lukasz answer.
Based on your update I would add the data as a parameter in the constructor and pass it in on instantiation:
<?php
require_once('class.php');
$data = [];
new myClass($data);
Adjusting your constructor to have the signature __construct(array $data)

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
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();
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

Codeigniter: Where to put the variable from a url

I am developing a stats site in Codeigniter locally. I have a url like localhost/sitename/player/show_profile/PlayerName
I currently have the following:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Player extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->model('player_model');
$player_name = $this->uri->segment(3);
}
public function index()
{
echo "index";
}
public function show_profile($player_name)
{
$data['player_stats'] = $this->player_model->get_stats( $player_name );
$this->load->view('player/player_stats', $data);
}
}
?>
This works, but my question is regarding the $player_name variable. I have $player_name = $this->uri->segment(3); in the __construct so it's available to all of the class methods. Is this the way I should be doing it?
Is this safe?
Fist of all, there is no point in assigning the variable in the constructor because it's going to get overwritten. When you pass CI a url like localhost/sitename/player/show_profile/PlayerName, anything passed the method (i.e. PlayerName) get's set as the parameters. Therefore, your variable in
public function show_profile($player_name){
is already set when you get to your method code.
Secondly, I agree with Peter's:
protected $player_name;
for making it globally accessible in the controller. BUT, I don't agree with setting it in the constructor. If you have another method in this controller that passes a variable in that spot, you're going to get the wrong data in there. Set it in the method you called:
public function show_profile($player_name){
$this->player_name = $player_name;
$data['player_stats'] = $this->player_model->get_stats( $player_name );
$this->load->view('player/player_stats', $data);
}
What you could do is define a class variable called $player_name and in the constructor set this to segment(3).
class Player extends CI_Controller
{
protected $player_name;
public function __construct() {
parent::__construct();
$this->load->model( 'player_model' );
$this->player_name = $this->uri->segment( 3 );
}
public function index() {
echo "index";
}
public function ( show_profile ) {
$data['player_stats'] = $this->player_model->get_stats( $this->player_name );
$this->load->view( 'player/player_stats', $data );
}
}
This way will be able to access the $play_name variable anywhere in the class.
You could also check to see if it's set using the $this->uri->uri_to_assoc(n) method and check to see if the key/value isset() http://codeigniter.com/user_guide/libraries/uri.html.
Peter

Accessing parent class objects & variables through $this?

I have one main class "main", which I use to store the configuration and a few objects. However, I am unable to access the objects & variables in a class which extends main, through $this.
Here is some of my main class:
<?php
class main{
// the configuration vars
public $config = array();
// the current user variables
public $uid; // contains the user ID
public $gid; // contains the group ID
// database variables
public $DB; // contains the connection
public $query_id; // contains the query ID
public $query_count; // how many queries have there been?
// cache variables
public $cache;
// start up functions
public function startup(){
// first, set up the caching
if(function_exists('memcache_connect') AND $this->config['use_memcache'] == true){
// start up memcache
require_once('memcache.class.php');
$this->cache = Cache::getInstance();
}
// now, set up the DB
$this->connectToDatabase();
// now, set up the user session
$this->setUserSession();
// are we logged in? If so, update our location
if($this->uid > 0){
// update location
$this->updateUserSession();
}
}
Here is an example of another class
<?php
class user extends main{
public function viewProfile($uid){
exit($this->config['session_prefix']); // displays nothing
if($this->cache->exists('key')){ // fails
The $config value is correctly set up, and I can read it within main but not any sub class.
The $cache->exists object just results in Call to a member function exists() on a non-object.
On index.php, the classes are loaded and set up. The Main class is setup first, and the startup function is called. The configuration array is passed before startup is called.
Can anyone suggest how I can fix this?
Are you sure your array is correctly set up.
This simple test works for me:
<?
class main {
public $test = "Woot";
}
class test extends main {
public function __construct() {
echo $this->test;
}
}
$t = new test();
Just for testing purposes, add a variable $test like in my example to the class main and try to echo it in the user constructor.
I would check if your cache is really set up correctly.
Probably the error is in this if statement:
if(function_exists('memcache_connect') AND $this->config['use_memcache'] == true){
One of these two conditions isn't met, so your $cache variable won't get initialized.
you can use parent:: to referance variables in the parent class.
parent::cache->exists('key')
You can access parent class's attributes by $this->attribute, so the problem should be that you are not calling the constructor of the parent...
Like this code is perfectly working:
<?php
class foo {
public $x="aa";
}
class bar extends foo {
public function barbar()
{
echo $this->x;
}
}
$b = new bar;
$b->barbar();
?>
Though you can also access parent class properties by Parent::attr()

Make controller constructor value global codeigniter

Im trying to get the total unread accounts from the database, the value is assigned to $data['head']
I want to make the $data['head'] available globally so it will be automatically loaded into the template and displayed on the header.
What is the best way to do this?
Below is my controller
function __construct()
{
parent::__construct();
$this->load->model('process_model');
$data['headbody']='includes/header';
$data['head'] = $this->process_model->loadnew($this->session->userdata('id'));
}
function invform()
{
$this->load->model('slave');
$data['body']='slave-account';
$data['questions'] = $this->slave->loadq($this->uri->segment(3));
$this->load->view('includes/template',$data);
}
View
$this->load->view($head);
$this->load->view($body);
$this->load->view('includes/footer');
You first need to make $data into a variable outside the function, using variable scope. Can be private or public. I made it private in this case.
Here's a quick revision:
private $data = array();
function __construct()
{
parent::__construct();
$this->load->model('process_model');
$this->data['headbody']='includes/header';
$this->data['head'] = $this->process_model->loadnew($this->session->userdata('id'));
}
function invform()
{
$this->load->model('slave');
$this->data['body']='slave-account';
$this->data['questions'] = $this->slave->loadq($this->uri->segment(3));
$this->load->view('includes/template',$this->data);
}
Notice the $this->data, instead of $data. When we're accessing variables within the same class, but outside of the function, we use $this.

Categories