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;
开发者_如何学JAVA $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.
Edit after comments: PHP's lack of support for named arguments (that would fix this problem altogether) is a much-lamented thing. In my experience, as long as there is no native solution to the problem, it is indeed better to declare each parameter separately for the purposes of automatic document generation and the lookup function in your IDE. The IDE can show the expected parameters only if they are explicitly declared.
See this SO question for another popular workaround to the issue.
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
private $fields = array("alpha", "beta", "gamma");
function __construct()
{
$args = func_get_args();
foreach ($args as $index => $arg)
{ $this->{($this->fields[index])} = $arg; }
}
this is not doing any checks on whether the specified variable exists - maybe add some more detail about what checks you exactly need.
You have a syntax error, this
foreach ($args as $arg -> $value)
Should be
foreach ($args as $arg => $value)
In the first example you would need to call
new gotClass($a, $b, $c)
But in your second example your expecting one array as a parameter so you would need to do
new gotClass(array($a, $b, $c))
You may want to refector and use func_get_args()
, using this will mean the following format will still work
new gotClass($a, $b, $c)
function __construct() {
$className = get_called_class();
$classAttributes = get_class_vars($className);
foreach (func_get_args() as $arg -> $value)
if (array_key_exists($arg, $classAttributes))
$this->$arg = $value;
}
精彩评论