【问题标题】:Noob PHP OOP Questions: Constructors and Curly Brackets菜鸟 PHP OOP 问题:构造函数和花括号
【发布时间】:2012-03-06 05:18:41
【问题描述】:

我正在尝试学习 OOP,但有几个问题。我已经阅读了PHP Objects, Patterns, and Practice 的前几章,以及以下帖子; Nettuts+PHP FreaksPHPRO

  1. 在子类中,构造函数是否必须列出父类中已经存在的变量?
  2. 当我在我的方法(或其他地方)中检索一个属性时,为什么我需要将我的值用大括号括起来(即 {$this->id})?
  3. 另外,如果有人有任何建议(例如我做错了什么),我愿意接受任何批评。

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


【解决方案1】:
  1. 没有。可以调用父类的构造函数。但是,如果您需要将此值作为参数接收,则需要为子类的构造函数提供额外的参数
  2. 当您在字符串中写入值并使用 -&gt; 运算符时,您需要将其包裹在花括号中,以便 PHP 知道您正在谈论的是成员,而不是 $this 本身。李>

【讨论】:

    【解决方案2】:

    2) 因为 php 在遇到一个不能在变量名中使用的字符(在本例中为“-”)时停止解析嵌入在引用字符串中的变量。然后它假定 - 只是字符串文字的一部分。当然,除非你用花括号把它包起来。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-28
      • 2023-03-05
      • 2011-02-19
      • 2012-05-09
      • 2019-11-11
      相关资源
      最近更新 更多