[nycphp-talk] Protected Constructor and Extended Classes
Scott Mattocks
scott at crisscott.com
Tue May 31 14:07:34 EDT 2005
Hello,
I have a question about constructor visibility in extended classes. Take
a look at this example:
<?php
class Goo {
public $stuff = '';
// Note the protected constructor.
protected function __construct($stuff)
{
$this->stuff = $stuff;
}
public function printStuff()
{
echo $this->stuff . "\n";
}
}
class Foo extends Goo {
public static function getGoo($stuff)
{
return new Goo($stuff);
}
}
$goo = Foo::getGoo('test stuff');
$goo->printStuff();
// This throws a fatal error as I would expect.
//$goo2 = new Goo('goo too');
?>
The subclass is allowed to call new Goo() even though the constructor is
declared protected. I understand that the constructor is visible to the
subclass and what not but something just seems off about this. I would
expect $this->__construct() to work fine but that has a whole different
effect. In my understanding the new operator is a public action even if
it is called within an extended class. Is this behavior expected? I want
to take advantage of this, but if it is going to be changed in a future
release I can't really depend on it.
Thanks,
--
Scott Mattocks
scott at crisscott.com
http://www.crisscott.com
More information about the talk
mailing list