簡體   English   中英

您如何訪問子 class 中的父 object 屬性

[英]how do you access the parent object property in child class

實際上,

這工作正常..但我想要父值。 不是子值..

<?php
    class Fruit{
        protected $parentproperty = "parentvalue";// this is parent value       
    }

    class Orange extends Fruit{
        protected $parentproperty = "child value";// here i mentioned once again        
        function showParentProperty(){
            return self::$this->parentproperty;
        }


    }
    $obj = new Orange;
    echo $obj->showParentProperty();

    //conclusion:
    // i want to get the parent value not child. its working fine . but it's displaying chid value


?>

如果你的意思是這樣的:

class Fruit {
    protected $parentproperty = "parent value";
}

class Orange extends Fruit{
    protected $parentproperty = "child value";
    function showParentProperty(){
        return $this->parentproperty; // corrected syntax here
    }
}

那么就沒有辦法做你想做的事,因為 PHP 中的所有非靜態 class 屬性實際上都是虛擬的。

如果父屬性為 static,則只能使用parent關鍵字,如下所示:

class Fruit {
    static $parentproperty = "parent value";
}

如果我們談論的是實例屬性,那么您唯一能做的就是為子屬性使用另一個名稱。

可以訪問在子 class 中被覆蓋的父 class 的非靜態屬性的默認值:

class Orange extends Fruit
{
    protected $parentproperty = "child value";
    function showParentProperty()
    {
        $parentProps = get_class_vars(get_parent_class($this));
        return $parentProps['parentproperty'];
    }
}

通過這種方式,您可以訪問父 class 的protectedpublic非靜態屬性,這在應用 DRY 原則時非常方便。

當您覆蓋子 class 中的 class 屬性 $parentproperty 時,我想來自父 class 的值丟失了。

我認為它會以這種方式工作。 您可以做的是在父級中聲明屬性,然后只要子級擴展父級,就可以直接在子級中訪問它們。 然后,在子 __constructor 中調用父 __constructor...

class fruit{
   protected $name;
   protected $type;

   __constructor($name, $type){
     $this->name = $name;
     $this->type = $type;
   }//end __constructor

}//end class

class thisFruit extends fruit{
   __constructor($name, $type){
      parent::__constructor($name, $type);
   }
}

你會使用它 $myFruit = new thisFruit("Orange", "Citrus"); echo "這個水果是一個 ".$myFruit->name;

希望這有幫助,祝你好運!

也許嘗試在父 class 中使用 __get($value) 並通過子調用它
public function __get($value){ if($value == 'parentValue'){ return parent::__get($value); }else{ return $this->$value; } }
我在我當前的項目中使用它並且工作正常。
科里

在您的孩子中:

function showParentProperty()
{
    return parent::$parentproperty;
}

沒有 static 屬性的唯一方法是使用反射 api

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM