如何编写一个构造函数来初始化类字段而不对字段名称进行硬编码
如何改进我的尝试:
class gotClass {
protected $alpha;
protected $beta;
protected $gamma;
(...)
function __construct($arg1, $arg2, $arg3, $arg4) {
$this->alpha = $arg1;
$this->beta = $arg2;
$this->gamma = $arg3;
(...)
}
}
像(针对评论进行编辑)这样的漂亮而紧凑的东西
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;
}
我无法让它工作,我不知道要使用正确的功能。我有没有提到我是 PHP 新手?非常感谢您的帮助。
编辑:字段名称不符合未经编辑的帖子可能建议的任何模式。因此它们的名称不能在某些类似 field[i] 的循环中构造。我很抱歉不清楚。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您需要执行此操作,则需要
func_get_args()
用于检索传递给构造函数的所有参数,以及用于映射属性名称的数组。像这样的事情
不会对指定的变量是否存在进行任何检查 - 也许会添加一些有关您确切需要的检查的更多详细信息。
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.
您有一个语法错误,这
应该是
在第一个示例中您需要调用
但在第二个示例中您期望一个数组作为参数,因此您需要这样做
您可能想要反射并使用
func_get_args()
,使用这个将意味着以下格式仍然会工作You have a syntax error, this
Should be
In the first example you would need to call
But in your second example your expecting one array as a parameter so you would need to do
You may want to refector and use
func_get_args()
, using this will mean the following format will still work