1

I have a simple form field with 3 input fields. I am trying to use the oop concept to write the code.
Is it good practice to get the request values in constructor, so that I can use these values in every method.

function __construct()
{
  $this->country = mosgetparam( $_REQUEST, 'country','');
  $this->month = mosgetparam( $_REQUEST, 'month','');
  $this->year = mosgetparam( $_REQUEST, 'year','');

}


This is just an older version of joomla. So no need to bother about the syntax.
Note: more info: I am submitting the form with country, month and year. I need these values to generate some reports. So is it okay to set the values in constructor so that I can get these values inside the methods?

Thejas
  • 353
  • 6
  • 19

2 Answers2

1

try

class MyClass {
   function __construct($country, $month, $year) {
       $this->country = $country;
       $this->month = $month;
       $this->year = $year; 
   }
}

var obj = new MyClass(mosgetparam( $_REQUEST, 'country',''),mosgetparam( $_REQUEST, 'month',''),mosgetparam( $_REQUEST, 'year',''));

you can do it this way. hope it helps :)

FastTurtle
  • 1,747
  • 11
  • 15
  • So if I have say more than 10 parameters to pass, this method is okay? Also is this completely depending on oop? Any suggestion to set and get values through class itself? – Thejas Mar 21 '16 at 06:50
  • this function follows oop concepts. this link will be helpful for getters and setters http://stackoverflow.com/questions/4478661/getter-and-setter – FastTurtle Mar 21 '16 at 06:55
1
class MyClass {

    protected $country;
    protected $month;
    protected $year;

    public function __construct($aParams)
    {
        foreach ($aParams as $sParam => $mValue) {
            if(property_exists(get_class($this), $sParam)){
                //ANY validation, including filter_var
                $this->$sParam = $mValue;
            }
        }
    }
}

$oMyClass = new MyClass(['month' => 'qqqqqq', 'year' => 34234]);
//OR
$oMyClass = new MyClass($_GET);
Mauricio Florez
  • 1,112
  • 8
  • 14