I
I
IdFox2016-01-17 12:49:05
Yii
IdFox, 2016-01-17 12:49:05

How to dynamically create a PHP class variable?

Hi everyone
, can you tell me how to create a class variable in a loop?
That is, for example, we have

<?php

class FormCompany extends Model {
    
    public $promo1_id, $promo2_id, $promo3_id;
    
}

?>

How can these variables be created in a loop?
If I try to specify in __construct $this->promo1_id = 111; then he swears that there is no such variable.
A cycle in the class itself (immediately after the class) cannot be done either.
How to simply create a variable (outside the class) - everything is clear and there are no questions, but in the class I don’t understand how to dynamically declare them (
In general, the meaning of the question - how to create these three variables (declare them and assign a value) in a loop
Thanks for the answers
PS
In general, it turned out that there is a problem with YII2
In PHP itself (pure), everything is created quite normally
<?php

error_reporting(E_ALL);
ini_set('display_error', 1);

class FormCompany {

public function __construct() {

$this->{'promo7_id'} = 111;

echo 'val: ' . $this->promo7_id;

}

}

$test = new FormCompany();

?>

If YII2 is used, then only the solution below
Although it seems to me that it is also not very beautiful ...

Answer the question

In order to leave comments, you need to log in

4 answer(s)
A
Andrzej Wielski, 2016-01-17
@IdFox

PHP does not forbid doing this, but YII has its own troubles and devils in the head.
You can (but don't) like this:

class FormCompany extends Model {
  public $promo;

  public function __construct(){
    $this->promo = (object)[];
    for($i = 1; $i < 10; $i++){
      $this->promo->{'var' . $i} = rand(0, 10);
    }
  }

}

The solution is quite cumbersome (for Yii2), but reassigning standard setters and getters is the only solution.
private $_attributes = ['test' => null]; //объвляем приватную переменную где будем объявлять без особых проблем переменные, и хранить их данные

    public function __get($name){
       if (array_key_exists($name, $this->_attributes)) //если переменная объявлена в нашем магическом массиве - выводим его значение
           return $this->_attributes[$name];

       return parent::__get($name); //либо стандартное
   }

   public function __set($name, $value){
       if (array_key_exists($name, $this->_attributes)) //аналог __get, только устанавливаем значение
           $this->_attributes[$name] = $value;

       else parent::__set($name, $value); //ну дефолтная установка значения
   }

   public function __construct(){
        parent::__construct(); //обязательно для Yii2, да и вообще в ООП при переназначении функций
        $this->__set('test', 'test'); // устанавливаем значение test
        $this->_attributes['newAttr'] = null; // объявляем новое значение
        $this->__set('newAttr', 'test value'); // и устанавливаем его значение
        $this->_attributes['newAttr'] = 'test value'; // хотя можно и так, как вам удобнее
   }

If you don't want to litter the code - again, try to cram all this into a helper, and connect it to the model through use.
From the view we get it as a normal parameter (for example Yii::$app->user->identity->test)
From the class via $this->__get('test')
Good luck!

M
Melkij, 2016-01-17
@melkij

If I try to specify in __construct $this->promo1_id = 111; then swears that there is no such variable

The question is not for PHP, but for your specific Model class (probably some kind of framework).
PHP allows you to add any new property to an object at any time and from anywhere.

V
Vyacheslav, 2016-01-17
@nskarl

class FormCompany extends Model {
  
  public $promo1_id = null;

  public function __construct()
  {
    $this->promo1_id = 111;
  }

  public function some()
  {
    print_r($this->promo1_id);
  }

}

N
Nikita, 2016-01-18
@bitver

What a difficult decision you noted ....

public function attributes()
    {
        return array_merge(parent::attributes(), [
            'test1', 'test2'
        ]);
    }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question