Answer the question
In order to leave comments, you need to log in
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;
}
?>
<?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();
?>
Answer the question
In order to leave comments, you need to log in
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 I try to specify in __construct $this->promo1_id = 111; then swears that there is no such variable
class FormCompany extends Model {
public $promo1_id = null;
public function __construct()
{
$this->promo1_id = 111;
}
public function some()
{
print_r($this->promo1_id);
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question