Re: Re: Enforce a constant in a class.
| From: | Richard Quadling | Date: | Mon, 25 Jan 2010 11:35:40 +0000 |
| Subject: | Re: Re: Enforce a constant in a class. | ||
| References: | 1 2 3 4 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-301408@lists.php.net to get a copy of this message | ||
2010/1/25 Pete Ford <pete@justcroft.com>:
> Richard Quadling wrote:
>>
>> 2010/1/22 Pete Ford <pete@justcroft.com>:
>>>
>>> IMHO, a constant is not the correct beastie in this case - if you want it
>>> to
>>> be different depending on the implementation then it ain't a constant!
>>>
>>> You should probably have protected static variables in the interface, and
>>> use the implementation's constructor to set the implementation-specific
>>> value (or override the default)
>>>
>>> interface SetKillSwitch
>>> {
>>> protected static $isSet = TRUE;
>>> protected static $notes;
>>> protected static $date = '2010-01-22T11:23:32+0000';
>>> }
>>>
>>> class KilledClass implements SetKillSwitch
>>> {
>>> public function __construct()
>>> {
>>> self::$isSet = FALSE;
>>> self::$date = '2010-01-21T09:30:00+0000';
>>> self::$notes = "Test";
>>> }
>>> }
>>>
>>> Cheers
>>> Pete Ford
>>
>> And of course, "Fatal error: Interfaces may not include member variables".
>>
>>
>>
>
> Ooops, sorry :)
>
> I tend to end up using abstract base classes rather than interfaces for that
> sort of reason...
>
> --
> PHP General Mailing List (http://www.php.net/)
> To unsubscribe, visit: http://www.php.net/unsub.php
>
>
Essentially I was starting with the idea that a subclass with constant
X _MUST_ have constant Y and Z. That's what I wanted to enforce.
But, finding that defined() was enough, I now realize that Y and Z are
_not_ mandatory, but they are constants. So simply ...
$KillSwitchNotes = defined(get_called_class() . '::KILL_SWITCH_NOTES') ?: Null;
is enough and now the whole _MUST_ is gone and is now optional.
Much better.
Thank you to everyone who chipped in. Old dog should really have known
that old trick!
--
-----
Richard Quadling
"Standing on the shoulders of some very clever giants!"
EE : http://www.experts-exchange.com/M_248814.html
EE4Free : http://www.experts-exchange.com/becomeAnExpert.jsp
Zend Certified Engineer : http://zend.com/zce.php?c=ZEND002498&r=213474731
ZOPA : http://uk.zopa.com/member/RQuadling