Watt
Watt

Reputation: 33

Declaring an abstract property from a subset

I'm building a Feed Reader abstract class to further declare adapters to read from various data sources. I would like to declare one of the properties (format) to be only within the selected subset (json, xml in this case) when defining the extended classes i.e.:

abstract Class FeedReader {
  public $url;
  //This is the line where I would like to define the type, but available only from a subset (json or xml).

  abstract function getData();
}


class BBCFeed extends FeedReader {
  public $type = 'json'; //I want this value to be restricted to be only json or xml

  function getData() {
    //curl code to get the data
  }
}

What is the most efficient (and correct) way of declaring the $type in the abstract class?. I want to restrict the $type to be only within a declared subset from the abstract class.

Thank you.

Upvotes: 3

Views: 41

Answers (1)

1sloc
1sloc

Reputation: 1180

You could use a class method to check the value.

<?php

abstract class FeedReader
{
  public $type;

  public function setType($type) {
    switch($type)
    {
    case 'json':
    case 'xml':
      $this->type = $type;
      break;
    default:
      throw new Exception('Invalid type');
    }
  }
}

class BBCFeed extends FeedReader
{
  public $type;

  public function __construct($type)
  {
    $this->setType($type)
  }

  function getData()
  {
  }
}

Upvotes: 1

Related Questions