I'd like to implement the following using a private constructor.
The problem is that get_class()
returns ParentBase
; eventhough; get_called_class()
returns ChildClass
.
How can I have __construct() be called from the calling class context instead of the base class context?
There will be many child classes, so I only want one shared factory method, and I also want to make sure a child cannot be extended (so that it cannot be created with the new keyword).
Seems like there should be a way of making ChildClass::createObject()
work with a private ChildClass
constructor and a public ParentBase
factory method.
<?php
class ParentBase
{
public static function createObject()
{
echo get_class() . "<br/>"; // prints ParentBase
echo get_called_class() . "<br/>"; // prints ChildClass
return new static();
}
}
class ChildClass extends ParentBase
{
private $greeting = "bye";
private function __construct()
{
$this->greeting = "hi";
}
public function greet()
{
echo $this->greeting;
}
}
$child = ChildClass::createObject();
$child->greet();
The output from the above is:
ParentBase
ChildClass
Fatal error: Call to private ChildClass::__construct() from context 'ParentBase'
Protected contstructor works: http://codepad.viper-7.com/sCgJwA
Private constructor doesn't: http://codepad.viper-7.com/YBs7Iz