I’m attempting to learn OOP and have a few questions. I’ve read the first few chapters in PHP Objects, Patterns, and Practice, as well as the following posts; Nettuts+, PHP Freaks, and PHPRO.
- In the child class, does the constructor have to list the variables that already exist in the parent class?
- When I retrieve a property in my methods (or other places), why do I need to wrap my values in curly brackets (i.e. {$this->id})?
- Also, if anyone has any advice (such as what I’m doing wrong), I’m open to any criticism.
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() . " />";
}
}
I spent a while attempting to get my code to display correctly in this post, but it keeps breaking.
->operator, you need to wrap it in curly braces so that PHP knows that you’re talking about a member, not$thisitself.