如何编写一个构造函数来初始化类字段而不对字段名称进行硬编码

发布于 2024-10-31 15:12:16 字数 957 浏览 1 评论 0原文

如何改进我的尝试:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

挽你眉间 2024-11-07 15:12:16

评论后编辑:PHP 缺乏对命名参数的支持(这将完全解决这个问题)是一件令人遗憾的事情。根据我的经验,只要问题没有本机解决方案,为了自动生成文档和在 IDE 中查找功能,确实最好单独声明每个参数。仅当显式声明预期参数时,IDE 才能显示这些参数。

请参阅此问题,了解该问题的另一种流行解决方法。< /p>

如果您需要执行此操作,则需要 func_get_args() 用于检索传递给构造函数的所有参数,以及用于映射属性名称的数组。

像这样的事情

private $fields = array("alpha", "beta", "gamma");

function __construct()
 { 
   $args = func_get_args();
   foreach ($args as $index => $arg)
    { $this->{($this->fields[index])} = $arg; }
 }

不会对指定的变量是否存在进行任何检查 - 也许会添加一些有关您确切需要的检查的更多详细信息。

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.

不及他 2024-11-07 15:12:16

您有一个语法错误,这

foreach ($args as $arg -> $value)

应该是

foreach ($args as $arg => $value)

在第一个示例中您需要调用

new gotClass($a, $b, $c)

但在第二个示例中您期望一个数组作为参数,因此您需要这样做

new gotClass(array($a, $b, $c))

您可能想要反射并使用 func_get_args(),使用这个将意味着以下格式仍然会工作

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;
}

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;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文