1

Say, I have a class with consts like so,

class Car
   {
      // Types
      const TYPE_SALOON = "Saloon";
      const TYPE_HATCHBACK = "Hatchback";
      ...

     public static function validTypes() {
          return array(
             static::TYPE_SALOON,
             static::TYPE_HATCHBACK,
             ...
          );
      }
 }

I need the constructor to accept an input argument called type, which exits in the array returned by validTypes(). The way I'd normally do this is:

function __construct($type, ...) {
    if(!in_array($type, static::validTypes())) {
        // Throw Exception
    }
}

What's a more elegant way to do this?

Is there a way to do this with typeHinting?

Zaxter
  • 2,939
  • 3
  • 31
  • 48
  • 1
    Not really. You pretty much need to resort to the solution you proposed there. – Frank Apr 16 '15 at 12:36
  • 1
    No, you can't typehint it in any way unless you used a CarType class; you need to test for this in your code in exactly the way you're doing – Mark Baker Apr 16 '15 at 12:36
  • 1
    @sergio `threw` is the past tense of throw, e.g. `I threw that stick for my dog`. `Through` is the word you're looking for, e.g. `I need to look through Stack Overflow for an answer to my problem`. – Styphon Apr 16 '15 at 12:46
  • Thanks Frank, Mark and sergio. php-arg-validator does provide a lot of options. I was thinking of enums with PHP and found this-> http://stackoverflow.com/questions/254514/php-and-enumerations – Zaxter Apr 16 '15 at 12:47
  • @Styphon and sergio, And I'll edit the question asking "Difference between threw and through", and who knows, maybe some moderator will migrate this question to english.stackexchange.com. – Zaxter Apr 16 '15 at 12:56

0 Answers0