cocktail builder (cocktailbuilder) wrote in php,
cocktail builder
cocktailbuilder
php

Inheritance and constants

I'm trying to push PHP5 OOP to the limit, and it's breaking instead of bending :) What am I doing wrong? 

Here's what I'd like to do - 

class Message {
   public static function getMessageType() {
     return self::MY_CONSTANT;
  }
}

class IncomingMessage extends Message {
   const MY_CONSTANT = "a";
}

class OutgoingMessage extends Message {
   const MY_CONSTANT = "b";
}

Then, I'd like to call OutgoingMessage::getMessageType(), and receive a valid value of the constant ("b")...Putting in a declaration of MY_CONSTANT into the base Message class doesn't help. 

Any ideas? What's a better way of doing this statically? I don't want to make the constant an object property, ad there are other elements in my interface that should be called statically. 

Here's me trying to do this through static class variables - returns "0" instead of "b":

class Message {
   public static function test() {
     return self::getMyConstant();
  }
 
  public static function getMyConstant() {
   return "0";
  }
}

class IncomingMessage extends Message {
   public static function getMyConstant() {return "a";}
}

class OutgoingMessage extends Message {
   public static function getMyConstant() {return "b";}
}

echo OutgoingMessage::test();

  • Post a new comment

    Error

    default userpic

    Your IP address will be recorded 

  • 12 comments