dsf45346 2019-01-26 17:45
浏览 93

PHP继承 - 具有子属性的父函数

Using PHP 5.4 - Company won't upgrade because it would break existing code. Sorry about that.

Say I have a class Resource:

class Resource {
  private $resourceIdentifier;

  public function __construct() {
    $this->resourceIdentifier = "ResourceId";
  }

  public function getIdentifier() {
    return $this->resourceIdentifier;
  }
}

Then, that class has a child:

class Employee extends Resource {
  public function __construct() {
    $this->resourceIdentifier = "EmployeeId";
  }
}

Then I create an instance of employee and call getIdentifier()

$emp = new Employee();
echo $emp->getIdentifier();

Will the function return $resourceIdentifier from the parent or the child?

On top of that, what will happen if I don't define $resourceIdentifier in the parent but I do in the child?

class Resource {
  public function getIdentifier() {
    return $this->resourceIdentifier;
  }
}

class Employee extends Resource {
  private $resourceIdentifier;

  public function __construct() {
    $this->resourceIdentifier = "EmployeeId";
  }
}
  • 写回答

2条回答 默认 最新

  • duanhunlou7051 2019-01-26 17:52
    关注

    If the $resourceIdentifier attribute is private, then the parent class cannot access it. You need to make it protected instead:

    class Employee extends Resource {
      protected $resourceIdentifier;
    
      public function __construct() {
        $this->resourceIdentifier = "EmployeeId";
      }
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 安装svn网络有问题怎么办
  • ¥15 Python爬取指定微博话题下的内容,保存为txt
  • ¥15 vue2登录调用后端接口如何实现
  • ¥65 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥15 latex怎么处理论文引理引用参考文献