0

I'm making a class and I want to be able to automatically assign variables being posted from an ajax request.

function assign_vars() {
    foreach($_POST as $index => $value) {
        if($index == 'car_year') {
            $this->car_year = $value;
        }
    }
}

This function would be very handy is their a cleaner way of doing this.

killkrazy
  • 127
  • 1
  • 1
  • 6

2 Answers2

0

Consider the following setup:

class ClassName
{
  /* Init with default values. */
  protected $_vars = array(
      'car_year' => null
    , ...
  );

  public function assign_vars( $array )
  {
    $this->_vars =
      array_merge($this->_vars, array_intersect_key($array, $this->_vars));
  }
}

$obj = new ClassName();
$obj->assign_vars($_POST);

In assign_vars(), array_merge() will overwrite values in $_vars, but only if they are already present (thanks to array_intersect_key()).

-1

Try with:

function assign_vars() {
    foreach($_POST as $index => $value) {
        $this->$index = $value;
    }
}

However the way you go is looking like not thought out solution.

hsz
  • 148,279
  • 62
  • 259
  • 315