php - oop PHP 多个构造函数

标签 php oop encapsulation

我正在从网站上单独学习 PHP。我有一些其他语言的 OOP 背景。
问题 1:
这是在 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; 
        }

    }
    }

最佳答案

  1. 在 PHP 中声明“多个”构造函数的方法有很多种,但没有一种是“正确”的方法(因为 PHP 技术上不允许这样做)。不过,我不认为你在那里的做法有什么问题。如果您想了解更多信息,请查看this Stack Overflow question .

  2. 您可以只使用 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/

相关文章:

java - 是关联还是聚合?

c++ - 未封装意味着不可更改?

php - Zend框架查询,添加到字符串

php - 调用未定义的方法 Stripe\Subscription::retrieve()

PHP检查SSN的长度

javascript - 使用ajax更新php页面使用post请求重新加载页面?

java - 代号一 showNativePicker() 方法问题

c - 为指向函数的指针编写一个 getter

java - 使用 ORM(例如 Ebean)是否会使封装变得不可能?值得关心吗?

php - 如何格式化从数据库接收到的日期和时间