我有一个包含3个输入字段的简单表单字段。我试图使用oop概念来编写代码。
在构造函数中获取请求值是一种好习惯,这样我就可以在每个方法中使用这些值。
function __construct()
{
$this->country = mosgetparam( $_REQUEST, 'country','');
$this->month = mosgetparam( $_REQUEST, 'month','');
$this->year = mosgetparam( $_REQUEST, 'year','');
}
这只是joomla的旧版本。所以不需要打扰语法。
注意:更多信息:我提交的表格包含国家,月份和年份。我需要这些值来生成一些报告。那么可以在构造函数中设置值,以便我可以在方法中获取这些值吗?
答案 0 :(得分:1)
试
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',''));
你可以这样做。
希望它有所帮助:)
答案 1 :(得分: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);