How to improve my attempt:
class gotClass {
protected $alpha;
protected $beta;
protected $gamma;
(...)
function __construct($arg1, $arg2, $arg3, $arg4) {
$this->alpha = $arg1;
$this->beta = $arg2;
$this->gamma = $arg3;
(...)
}
}
to something nice and compact like (edited in response to comments)
class gotClass {
protected $alpha;
protected $beta;
protected $gamma;
(...)
function __construct($alpha, $beta, $gamma) {
$functionArguments = func_get_args();
$className = get_called_class();
$classAttributes = get_class_vars($className);
foreach ($functionArguments as $arg => $value)
if (array_key_exists($arg, $classAttributes))
$this->$arg = $value;
}
I can’t get it work, I don’t know the right functions to use. Did I mention I’m new to PHP? Your help is much much appreciated.
EDIT: The field names do not conform to any pattern as the unedited post may have suggested. So their names cannot be constructed in some field[i]-like loop. My apologies for being unclear.
If you need to do this anyway, you need
func_get_args()to retrieve all arguments passed to the constuctor, and an array to map the property names.Something like
this is not doing any checks on whether the specified variable exists – maybe add some more detail about what checks you exactly need.