Noob PHP OOP问题:构造函数和卷曲支架
问题描述:
我正在尝试学习OOP并有几个问题。我已阅读了PHP Objects, Patterns, and Practice的前几章,以及以下帖子; Nettuts+,PHP Freaks和PHPRO。Noob PHP OOP问题:构造函数和卷曲支架
- 在子类中,构造函数是否必须列出已经存在于父类中的变量?
- 当我在我的方法(或其他地方)中检索一个属性时,为什么我需要将我的值包裹在大括号中(即{$ 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() . " />";
}
}
我花了一段时间试图让我的代码,在这篇文章中正确显示,但它不断地刷新。
答
- 不可以。您可以调用父类的构造函数。但是,如果需要将此值作为参数,则需要为子类的构造函数提供额外参数
- 当您在字符串中编写值并使用
->
运算符时,需要将其包装在大括号中,以便PHP知道你在说的是一个成员,而不是$this
本身。
答
2)因为PHP解析停止嵌入引用的字符串变量,当它到达一个字符变量名中使用无效的(在这种情况下,“ - ”)。然后它假设 - 只是字符串文字的一部分。当然,除非你用花括号包裹它。
哇......那是有史以来最诡异的经历,试图鳕鱼在SO上格式化一个帖子...有关该有序列表的东西......必须抛出规则才能使其运行。 – prodigitalson 2012-03-06 05:34:08