Abilash Erikson
Abilash Erikson

Reputation: 351

if ( ! defined ) is not working inside class in php

i want to define a constant and set a random value to this . Please see my code below

class ABC {
  public function __construct() {
     $this->my_constant();
  }
  public function my_constant(){
     define ('RANDOM_CONSTANT', uniqid());
  }


}

Here I can call RANDOM-CONSTANT but the problem is each time I am getting different value. So I want to fix that value and it doesn't need to change always. So i tried the following

   public function my_constant() {
       if (! defined('RANDOM_CONSTANT') ) {
        define ('RANDOM_CONSTANT', uniqid());
       }
   }

But still the constant value change once the page get refreshed. How to solve this?

Upvotes: 0

Views: 39

Answers (1)

donatJ
donatJ

Reputation: 3374

But still the constant value change once the page get refreshed. How to solve this?

PHP does not hold any state between page refreshes. Every page load is generated entirely clean and fresh. This means your constant is only defined until the end of the page load, and then it's forgotten forever.

To get the same unique id across page loads you would need to use either session handling which would make it unique per user, or some sort of database.

Upvotes: 1

Related Questions