M
M
Max Ba2020-05-20 13:02:28
PHP
Max Ba, 2020-05-20 13:02:28

How to create a property inside a method?

Tired of working with an array. I want to change the method

public function setData(array $data):void{
  $this->data = $data;
}

on the
public function setData(array $data):void{
  foreach($data as $k => $v){
    $this->$k = $v;
  }
}

1. Do they do it?
2. How to do it?) I tried using __set, I didn’t understand something. This is the first time I have encountered such a need.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
T
ThunderCat, 2020-05-20
@phpcoder81

1. Do they do it?
They do, but it's not good practice. Firstly, you have a chance to erase some of the object's configuration data and get unpredictable behavior. Secondly, if you have values ​​from a database or other storage in the key-value format, it is better to store them in a separate field, the same date, but in the form of stdClass, so as not to confuse them with other fields when working with storage, like this:
public function setData(array $data):void{
  $this->data = (object)$data;
}

Ideally, you should have a DTO (data transfer object), but it is usually not used in asset record engines.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question