views:

32

answers:

2

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");
A: 

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.

Alan Geleynse
Well, it seems that I found out where the problem. was. I misinterpreted the task. It's all doable if constructors are public, and attributes/methods are protected.
Marian
Yes, making a constructor private or protected has very specific uses but is not a good idea most of the time.
Alan Geleynse
I made assumption that constructor needs to be protected, because attributes/methods needed to be protected. Task description didn't say anything about access zone (?) of constructors. Thanks everyone. Sorry for wasting a couple minutes of your time.
Marian
A: 

Actually it's doable, because every PHP object has magic methods with predefined method visibilities.

class Test {

    protected function __construct() {
        print "Constructing";
    }

    protected function hello() {
        print "Hello World";
    }

    protected static function create() {
        return new self;
    }

    static function __callStatic($name, $arguments) {
        if ($name === 'create') {
            return self::create();
        }
    }

    function __call($name, $arguments) {
        if (method_exists($this, $name)) {
            return call_user_func_array(array($this, $name), $arguments);
        }
    }
}

$test = Test::create();
$test->hello();
Saul