开发者

PHP accessing protected constructor

开发者 https://www.devze.com 2023-01-22 06:08 出处:网络
I know it is very uncommon to use protected methods or constructors. I have read discussions about this on SO and other sites.

I know it is very uncommon to use protected methods or constructors. I have read discussions about this on SO and other sites. The task I've got is rat开发者_如何学JAVAher simple. I have to access protected methods/constructors from my program. All attributes/methods must be declared as protected.

My code can be reduced to this. I'm basically asked to do this with the easiest/simplest way. All solutions I can think of either use some more advanced technique ("friends" etc) or a public function, which is against the rules.

Thank you.

     class one
        {
         protected $attribute1;
        }

        class two extends one
        {
         protected $attribute2;
         protected $attribute3;
            protected function __construct($arg1, $arg2, $arg3)  
         {
          $this->attribute1= $arg1;
          $this->attribute2= $arg2;
          $this->attribute3= $arg3;

            }
        }

$object = new two(" 1", "2", "3");


The purpose of a private or protected constructor is to prevent the class from being instantiated from outside of the class.

You could create a public static function in the class that returns a new object, but you cannot create it directly if you want to have the constructor be protected or private. You must have something declared as public or you cannot use the class.

0

精彩评论

暂无评论...
验证码 换一张
取 消