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 關注
- 229 瀏覽
添加回答
舉報