繁体   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