【问题标题】:Declaring an abstract property from a subset从子集中声明抽象属性
【发布时间】:2016-07-10 15:20:34
【问题描述】:

我正在构建一个 Feed Reader 抽象类,以进一步声明要从各种数据源读取的适配器。在定义扩展类时,我想声明一个属性(格式)仅在选定的子集(在这种情况下为 json、xml)内,即:

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
  }
}

在抽象类中声明 $type 最有效(和正确)的方法是什么?我想将 $type 限制在抽象类声明的子集中。

谢谢。

【问题讨论】:

  • abstract function getType() 怎么样?
  • @D.Dimitrioglo 我认为它仍然允许子类定义任何类型。

标签: php properties abstract


【解决方案1】:

您可以使用类方法来检查该值。

<?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()
  {
  }
}

【讨论】:

  • 看起来不错,符合我的预期:)
猜你喜欢
  • 1970-01-01
  • 2023-03-20
  • 1970-01-01
  • 2023-03-28
  • 2020-04-12
  • 2011-05-13
  • 2011-01-13
  • 1970-01-01
  • 2011-01-13
相关资源
最近更新 更多