Re: Enforce a constant in a class.

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



One way to do it would be to use getter functions in your interface
that return the value of the constant (or a member variable) in your
implemented class. For example:

interface SetKillSwitch {
       public function getKillSwitchNotes();
}

Then in your class implement your getKillSwitchNotes function:

class KilledClass implements SetKillSwitch {
       const KILL_SWITCH_NOTES = 'Some notes';

      public function getKillSwitchNotes()
      {
          return SetKillSwitch::KILL_SWITCH_NOTES;
      }
}

On Fri, Jan 22, 2010 at 11:33 AM, Richard Quadling
<rquadling@xxxxxxxxxxxxxx> wrote:
> Hello,
>
> One of the aspects of an interface is to enforce a public view of a
> class (as I see it).
>
> Within PHP, interfaces are allowed to have constants, but you cannot
> override them in a class implementing that interface.
>
> This seems wrong.
>
> The interface shouldn't define the value, just like it doesn't define
> the content of the method, it only defines its existence and requires
> that a class implementing the interface accurately matches the
> interface.
>
> Is there a reason for this behaviour?
>
>
>
> _OR_
>
> How do I enforce the presence of a constant in a class?
>
> <?php
> interface SetKillSwitch {
>        const KILL_SWITCH_SET = True;
>
>        // Produces an error as no definition exists.
>        // const KILL_SWITCH_NOTES;
>
>        // Cannot override in any class implementing this interface.
>        const KILL_SWITCH_DATE = '2010-01-22T11:23:32+0000';
> }
>
> class KilledClass implements SetKillSwitch {
>        // Cannot override as defined in interface SetKillSwitch.
>        // const KILL_SWITCH_DATE = '2010-01-22T11:23:32+0000';
> }
> ?>
>
> I want to enforce that any class implementing SetKillSwitch also has a
> const KILL_SWITCH_DATE and a const KILL_SWITCH_NOTES.
>
> I have to use reflection to see if the constant exists and throw an
> exception when it doesn't.
>
> The interface should only say that x, y and z must exist, not the
> values of x, y and z.
>
> Regards,
>
> Richard.
>
> --
> -----
> 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
>
> --
> PHP General Mailing List (http://www.php.net/)
> To unsubscribe, visit: http://www.php.net/unsub.php
>
>

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux