从一个子集中声明一个抽象 属性
Declaring an abstract property from a subset
我正在构建一个 Feed Reader 摘要 class 以进一步声明适配器以从各种数据源读取。我想在定义扩展的 classes 即:
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
}
}
在摘要 class 中声明 $type 的最有效(和正确)方法是什么?。我想将 $type 限制在抽象 class.
的声明子集中
谢谢。
您可以使用 class 方法来检查该值。
<?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()
{
}
}
我正在构建一个 Feed Reader 摘要 class 以进一步声明适配器以从各种数据源读取。我想在定义扩展的 classes 即:
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
}
}
在摘要 class 中声明 $type 的最有效(和正确)方法是什么?。我想将 $type 限制在抽象 class.
的声明子集中谢谢。
您可以使用 class 方法来检查该值。
<?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()
{
}
}