duanliyi5997 2014-09-18 00:33
浏览 43

PHP,使用父类属性作为子类中的另一种类型

i got 2 class Node and ChildNode, ChildNode extends Node. There property in parent:

class Node {
    protected $discount;
    public function __construct($discount) {
        $this->discount = $discount;

and i use it there like integer value, in the ChildNode i need to hold array of integer values

class ChildNode extends Node {
    public function __construct(Array $discount) {
        $this->discount = $discount; 

Is it normal to do like this?

  • 写回答

1条回答 默认 最新

  • duanlianyun0462 2014-09-18 00:52
    关注

    I don't see any issue with this. If you have multiple classes that will all benefit from a parent class structured this way it makes it easy to add another method or another variable to all of the child classes at once in the future. I also checked to see how PHP handles inheritance since I was not 100% sure on this and also because php will automagically set variables for you if you assign to something like $this->doesnotexistyet = "magic!"; however the below outputs the following...

    class A {
    
        protected $d;
    
        public function __construct() {
            $this->d = "A";
        }
    
        public function getDP() {
            return $this->d;
        }
    
    }
    
    class B extends A {
    
        public function __construct() {
            $this->d = "B";
        }
    
        public function getD() {
            return $this->d;
        }
    
    }
    
    $a = new A();
    echo $a->getDP() . PHP_EOL;
    
    $b = new B();
    echo $b->getD() . PHP_EOL;
    echo $b->getDP() . PHP_EOL;
    
    var_dump($a , $b);
    

    Output.

    A
    B
    B
    object(A)#1 (1) {
      ["d":protected]=>
      string(1) "A"
    }
    object(B)#2 (1) {
      ["d":protected]=>
      string(1) "B"
    }
    

    This was more for me than anything but thought I would add it if it helps others who come across this.

    评论

报告相同问题?

悬赏问题

  • ¥15 有偿四位数,节约算法和扫描算法
  • ¥15 VUE项目怎么运行,系统打不开
  • ¥50 pointpillars等目标检测算法怎么融合注意力机制
  • ¥15 关于超局变量获取查询的问题
  • ¥20 Vs code Mac系统 PHP Debug调试环境配置
  • ¥60 大一项目课,微信小程序
  • ¥15 求视频摘要youtube和ovp数据集
  • ¥15 在启动roslaunch时出现如下问题
  • ¥15 汇编语言实现加减法计算器的功能
  • ¥20 关于多单片机模块化的一些问题