L
L
Leopandro2016-07-01 11:52:26
Yii
Leopandro, 2016-07-01 11:52:26

How to write functions that work with variable names as object property names?

The bottom line is this: there are 3 functions for working with pictures

public $drivePath = '@app/web/files/images/drivers/';
  public $webPath = '/web/files/images/drivers/';

  public function uploadImage()
  {
    if (!$this->image)
      return false;
    $path = Yii::getAlias($this->drivePath.$this->car_id.'/');
    if (!is_dir($path)) mkdir($path, 0777, true);
    $filename = Yii::$app->security->generateRandomString(9);
    $this->image->saveAs($path . $filename . '.' . $this->image->extension);
    $this->image = $filename . '.' . $this->image->extension;
    return true;
  }

  public function getImage()
  {
    $path = Yii::getAlias($this->webPath.$this->car_id.'/'.$this->image);
    return Html::img($path, [
      'height' => '100px',
      'width' => 'auto'
    ]);
  }

  public function deleteImage()
  {
    $path = Yii::getAlias($this->drivePath.$this->car_id.'/'.$this->oldAttributes['image']);
    if (file_exists($path))
      unlink($path);
  }

In order to make it more universal, one moment is missing - the function each time accesses a certain property of the object, the name of this variable may change. How to make it refer to the property, let's say $this->photo_image and we have $this->image everywhere. Someone might say that you can pass a variable there, $this->photo_image. But it will be much more convenient if the name of the property is stored in the settings than to remember it with each action and pass it to the function as a parameter.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Makarov, 2016-07-01
@Leopandro

$class->{$propertyName}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question