gpt4 book ai didi

php - oop PHP 不止一个构造函数

转载 作者:行者123 更新时间:2023-12-04 05:48:40 24 4
gpt4 key购买 nike

我正在从网站上单独学习 PHP。我对其他语言有一些 OOP 背景。

问题一:

这是在 PHP 中使用 2 组不同参数实现构造函数的正确方法吗?

问题2:

当我来到 PHP 中的 __set 魔术方法时,我希望这个类中的 comment_id 不能从 __set 函数中更改。这可以在 PHP 中完成吗?

 class Comment{
private $comment_id;
private $image_id;
private $author_id;
private $comment_text;
private $created_at;

public function __construct()
{
$arguments = func_get_args();
$num = sizeof($arguments)
switch($num)
{
case 0;
break;
case 3:
this->image_id = $arguments[0];
this->author_id = $arguments[1];
this->comment_text = $argument[2];
break;
case 5:
this->comment_id = $arguments[0];
this->image_id = $arguments[1];
this->author_id = $argument[2];
this->comment_text = $argument[3];
this->created_at = $argument[4];
break;
default:
break;

}
}

public function __get($property)
{
if(property_exists($this,$property))
{
return $this->$property;
}
}

public function __set($property_name,$value)
{
if(property_exists($this,$property_name))
{
$this->$property_name = $value;
}

}
}

最佳答案

  • 在 PHP 中有多种声明“多个”构造函数的方法,但没有一种方法是“正确”的(因为 PHP 技术上不允许这样做)。但是,我认为您在那里的做法没有任何问题。如果您想了解更多信息,请查看 this Stack Overflow question .
  • 你可以只使用 if陈述。像这样的东西,也许?

    public function __set($property_name,$value)
    {
    $hidden_properties = array(
    'comment_id',
    'any_other_properties'
    );

    if(!in_array($property_name, $hidden_properties) &&
    property_exists($this, $property_name))
    {
    $this->$property_name = $value;
    }
    }
  • 关于php - oop PHP 不止一个构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10371335/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com