G
G
Good Samaritan2018-06-11 13:36:42
Yii
Good Samaritan, 2018-06-11 13:36:42

How to understand the following code?

There is a method

public function myRule($attribute, $params)
  {
    if (!in_array($this->$attribute, ['USA', 'world'])){
      $this->addError($attribute, 'Страна должна быть либо "USA" или "Indonesia".');
    }
  }

What does $this->$attribute refer to in this code?
To check the argument of a method, it was necessary like if (!in_array($attribute, ['USA', 'world']))
this. Why is this needed here?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
davidnum95, 2018-06-11
@djamali

What does $this->$attribute refer to in this code?

public function rules() {
  return [
    ['country', 'myRule']
 ];
}

public function myRule($attribute, $params)
  {
    //$attribute == 'country' - поле в модели
    //$this->$attribute == $this->country - значение поля в модели
    if (!in_array($this->$attribute, ['USA', 'world'])){
      $this->addError($attribute, 'Страна должна быть либо "USA" или "Indonesia".');
    }
  }

A
Anton Shamanov, 2018-06-11
@SilenceOfWinter

check out the implementation of OOP in php

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question