更改子类 PHP 中的属性



我想创建一个不同的类,只有一个具有不同值的变量,其他所有内容都应该与父类相同。

这里是父类

class parentClass {
    private $param_name_saved = 'files';
        protected $image_objects = array();
        function __construct($options = null, $initialize = true, $error_messages = null) {
            $this->options = array(
                'script_url' => $this->get_full_url().'/',
                'upload_dir' => dirname($this->get_server_var('SCRIPT_FILENAME')).'/files/2',
                'upload_url' => $this->get_full_url().'/files/2',
                'user_dirs' => false,
                'mkdir_mode' => 0755,
                'param_name' => $this->param_name_saved,
                'tost' => 'files',
                // Set the following option to 'POST', if your server does not support
                // DELETE requests. This is a parameter sent to the client:
                'delete_type' => 'DELETE',
                'access_control_allow_origin' => '*',
                'access_control_allow_credentials' => false,
                'access_control_allow_methods' => array(
                    'OPTIONS',
                    'HEAD',
                    'GET',
                    'POST',
                    'PUT',
                    'PATCH',
                    'DELETE'
                )
    } 
}

我想为属性 $param_name_save 创建具有不同值的子类

这就是我想要创造的

class childClassone extends parentClass {
        private $param_name_saved = 'files3';
}
class childClasstwo extends parentClass {
        private $param_name_saved = 'files2';
}

当我使用上面的代码时,我在这里做错了什么?

您必须更改一些内容:

  1. parentClass::$param_name_saved的可见性更改为受保护。
  2. 更新子类的构造函数。

所以:

class parentClass 
{
    protected $param_name_saved = 'files';
    // ...
}
class childClassone extends parentClass 
{
    function __construct($options = null, $initialize = true, $error_messages = null) 
    {
        $this->param_name_saved = 'files3';
        parent::__construct($options, $initialize, $error_messages);
    }
}

私有属性对子类不可见。

可以将可见性更改为受保护,也可以在父类上添加函数setParamNameSaved,并在子类上调用此函数以更改属性param_name_saved

最新更新