-
Notifications
You must be signed in to change notification settings - Fork 21
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Constructor Trait? #27
Comments
Probably |
So I've been rattling this one around in my brain, and I don't see how this is possible without setting a class property? |
Is it not possible to add a private ctor? |
I think we are talking about addressing two different things here. Yes private constructors can be added. I was referring to preventing a class constructor from executing more than once. |
Ok, that is something I misread while scanning the notifications, sorry. I think it can be done, but it's hard to do so without introducing more state in a class. I would suggest going the easy way first: add a As for making it work with generic constructors, it becomes really tricky, but I've done it in |
Here is how I see it going down. This is just pseudo code... Exceptions will be replaced with proper ones once I start coding. @Ocramius - You are by far a better PHP programmer than me, so I wanted to check to see if this is what you had in mind? <?php
declare(strict_types=1);
namespace Dont;
trait DontInstantiateTwice
{
/**
* constructorHasInited
* Has the constructor inited?
*
* @var bool
* @internal
*/
private $constructorHasInited = false;
private function initConstructor(): void
{
if ($this->constructorHasInited===true)
{
throw Exception('reserved for future message');
}
$this->constructorHasInited = true;
}
} Pseudo Usage <?php
use Dont\DontInstantiateTwice;
class Foo
{
use DontInstantiateTwice;
/**
* __construct
* Do some busy work
* ...
*
* @throws Exception - When the __construct is called more than once
* per instantiated object
*/
public function __construct()
{
//doing some busy work
//...
$this->initConstructor();
}
} |
|
Agreed |
Hi,
Would it be a good idea to have a trait that prevents the class constructor(s) from running more than once? I would be more than willing to code this up, I just have no idea what to call it.
The text was updated successfully, but these errors were encountered: