Yii create a new attribute in the model doesn't work

117 Views Asked by At

I need to create a new attribute in the model and something weird is happening:

this code, works fine:

class Person extends CActiveRecord {

   public $test = "xxx";

   public function getRandomToken() {
      $temp = $this->test;
      return $temp;
   }

this code, does not:

class Person extends CActiveRecord {

   public $test = md5(uniqid(rand(), true));

   public function getRandomToken() {
      $temp = $this->test;
      return $temp;
   }

why? I get a blank page with the second code, with no errors.

I will need to use the random token from create view-page and I'm doing it in this way:

echo $model->getRandomToken();

Thank you for your support!

2

There are 2 best solutions below

3
On BEST ANSWER

If you do not want to overwrite the contructor you can use this:

class Person extends CActiveRecord {

   public $test = null;

   public function getRandomToken() {
      if ($this->test == null){
        $this->test = md5(uniqid(rand(), true));
      }
      $temp = $this->test;
      return $temp;
   }
4
On

You cannot assign a function result as value. It must be a constant. Assign the function value in the constructor

public $test = '';

function __construct() {
    $this->test = md5(uniqid(rand(), true));
}