phpyiicactiverecord

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


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!


Solution

  • 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;
       }