2 回答
TA贡献1752条经验 获得超4个赞
看起来像一个糟糕的设计模式。对我来说,一个国家可以包含几个不同的城市。因此,城市不是国家。你的国家实体类不应该是这样的吗?
class Country
{
/**
* Collection of City objects
* @var ArrayObject
*/
protected $cities;
protected $name;
protected $population;
protected $language;
public function setCity(City $city) : self
{
if ($this->cities == null) {
$this->cities = new ArrayObject();
}
$this->cities->append($city);
return $this;
}
public function getCities() : ArrayObject
{
if ($this->cities == null) {
$this->cities = new ArrayObject();
}
return $this->cities;
}
}
无论如何......让我们用php自己的反射类来解决您的问题。要获取声明类的属性,只需在城市类中实现以下功能即可。
class City extends Country
{
public $populationCity;
public function getData() : array
{
$data = [];
$reflection = new ReflectionClass($this);
$properties = $reflection->getProperties(ReflectionProperty::IS_PUBLIC);
foreach ($properties as $property) {
if ($property->getDeclaringClass() == $reflection) {
$data[$property->getName()] = $property->getValue($this);
}
}
return $data;
}
}
有了这个,您只能获取City类的属性。让我们试一试...
$city = new City();
$city->populationCity = 10000;
var_dump($city->getData());
希望这可以帮助。
- 2 回答
- 0 关注
- 194 浏览
添加回答
举报