Instantiate without constructor
Closed this issue · 5 comments
Usecase is e.g. custom deserialization like what https://github.com/xp-forge/marshalling does. PHP has ReflectionClass::newInstanceWithoutConstructor()
for this.
First idea would be to hook on to constructor because this only applies for the case that a constructor already exists, and pass NULL instead of an array for arguments, e.g.:
if ($constructor= $type->constructor()) {
$instance= $constructor->newInstance(null);
} else {
$instance= $type->newInstance();
}
However, from a readability point of view, this would still imply something is done with the constructor, which is not what's happening. Maybe then:
if ($constructor= $type->constructor()) {
$instance= $constructor->bypass();
} else {
$instance= $type->newInstance();
}
Another idea would be to follow the idea of a generated constructor returned by the constructor()
accessor:
$instance= $type->constructor(true)->newInstance();
Instead of true, we could also use constants like Constructor::SYNTHETIC
or Constructor::GENERATED
.
Or we pass a construction function:
$instance= $type->constructor(function() { })->newInstance();
This way, we have complete control over object instantiation.