亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何創建一個只繼承方法而不繼承父類屬性的子類?

如何創建一個只繼承方法而不繼承父類屬性的子類?

PHP
米琪卡哇伊 2021-10-15 17:47:43
假設我有這個代碼:首先我創建了父級 class Country {  public $country;  public $populationcountry;  public $language;     使用一些方法(與此問題無關)public function function1() {   }public function function2() {    }             .             .                }  //end of parent class然后我創建了孩子 Class city extends Country {public $populationcity;} 然后我創建對象(對于這個例子,我只創建了一個)$city1 = new city();$city1->populationcity = 10000; 和一組對象$cities = [$city1];    最后我只想“回顯”孩子的屬性(人口城市)foreach ($cities as $city) {foreach ($city as $k => $v) {$city->populationcity;echo $k . ': ' . $v . '<br>'; }}   輸出:人口城市:10000國家:人口國家:語言:我想保留父級的方法,而不是父級的屬性。我怎樣才能做到這一點?David 在評論中告訴我將屬性設置為 Private。我這樣做了,并且工作正常,但是當我創建 Country 對象時,它會在子類中打印父類的屬性。這是代碼,當父屬性為 Public 時,它為我提供此輸出。人口城市:10000國家:人口國家:語言:國家:英格蘭人口國家:30000語言:英語它應該打?。喝丝诔鞘校?0000國家:英格蘭人口國家:30000語言:英語當我將它們設置為 Private 時,我得到了這個:致命錯誤:未捕獲錯誤:無法訪問 C:\xampp\htdocs\ejercicios.php:141 中的私有屬性 Country::$language 堆棧跟蹤:#0 {main} 拋出在 C:\xampp\htdocs\ejercicios.php 中141當我將它們設置為 Protected 時,我得到了這個:致命錯誤:未捕獲的錯誤:無法訪問 C:\xampp\htdocs\ejercicios.php:141 中的受保護屬性 Country::$language 堆棧跟蹤:#0 {main} 拋出在 C:\xampp\htdocs\ejercicios.php 141
查看完整描述

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());

希望這可以幫助。


查看完整回答
反對 回復 2021-10-15
  • 2 回答
  • 0 關注
  • 229 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號