w0lf42
w0lf42

Reputation: 528

Noob PHP OOP Questions: Constructors and Curly Brackets

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.

  1. In the child class, does the constructor have to list the variables that already exist in the parent class?
  2. 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})?
  3. 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.

Upvotes: 1

Views: 361

Answers (2)

Jonathon Reinhart
Jonathon Reinhart

Reputation: 137398

2) Because php stops parsing variables embedded in quoted strings when it reaches a character invalid for use in a variable name (in this case '-'). It then assumes the - is just part of the string literal. Unless, of course, you wrap it in curly braces.

Upvotes: 2

Rafe Kettler
Rafe Kettler

Reputation: 76955

  1. No. You can call the constructor of the parent class. If you need to take in this values as arguments, though, you'll need to have extra parameters for the child class's constructor
  2. When you're writing a value in a string and using the -> operator, you need to wrap it in curly braces so that PHP knows that you're talking about a member, not $this itself.

Upvotes: 3

Related Questions