Marian
Marian

Reputation: 1

PHP accessing protected constructor

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 rather 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");

Upvotes: 0

Views: 9718

Answers (1)

Alan Geleynse
Alan Geleynse

Reputation: 25139

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.

Upvotes: 5

Related Questions