【发布时间】:2012-03-06 05:18:41
【问题描述】:
我正在尝试学习 OOP,但有几个问题。我已经阅读了PHP Objects, Patterns, and Practice 的前几章,以及以下帖子; Nettuts+、PHP Freaks 和 PHPRO。
- 在子类中,构造函数是否必须列出父类中已经存在的变量?
- 当我在我的方法(或其他地方)中检索一个属性时,为什么我需要将我的值用大括号括起来(即 {$this->id})?
- 另外,如果有人有任何建议(例如我做错了什么),我愿意接受任何批评。
class Element {
public $tag;
public $id;
function __construct( $tag, $id ) {
$this->tag = $tag;
$this->id = $id;
}
public function getAttributes() {
return "id='{$this->id}'";
}
}
class NormalElement extends Element {
public $text;
function __construct( $tag, $id, $text ) {
parent::__construct( $tag, $id );
$this->text = $text;
}
public function getElement() {
return "<{$this->tag}>{$this->text}</{$this->tag}>";
}
}
class VoidElement extends Element {
function __construct( $tag, $id ) {
parent::__construct( $tag, $id );
}
public function getElement() {
return "<{$this->tag} " . parent::getAttributes() . " />";
}
}
我花了一段时间试图让我的代码在这篇文章中正确显示,但它一直在出错。
【问题讨论】:
-
哇...那是尝试在 SO 上编排帖子格式的最奇怪的体验...关于该有序列表的某些内容...必须加入规则才能使其正常工作。
标签: php oop constructor