【问题标题】:why are php extended class properties not updated为什么php扩展类属性没有更新
【发布时间】:2020-12-14 14:39:37
【问题描述】:

我正在尝试扩展 DateTime,如下所示:

class testdate extends DateTime {
public $sqldate;

public function __construct($time)
{
    parent::__construct($time);
    //?? parent::modify();

    $this->sqldate = $this->format ("Y-m-d"); 
}

}
echo "<pre>";

$td = new testdate("2020-08-23");
echo "       Today's Date: ".$td->format ("m/d/Y").br;
echo "   Today's SQL Date: ".$td->sqldate.br.br;
$td->modify ("+24 hour");
echo "    Tomorrow;s Date: ".$td->format ("m/d/Y").br;    // 1 day added correctly
echo " Tomorrow Formatted: ".$td->format ("Y-m-d").br;
echo "  Tomorrow Sql Date: ".$td->sqldate.br.br;          //not updated
print_r ($td);

正如您在 print_r 语句中看到的,日期已更新,但 sqldate 未更新。

我必须做些什么来确保扩展类的属性得到更新?

【问题讨论】:

  • 您没有包含print_r 的结果。这将有助于显示这些回声的确切输出。
  • $this-&gt;sqldate 在调用$td-&gt;modify() 时不会更新。您还需要覆盖 modify() 方法。
  • 或者只是让sqldate 成为一个方法,而不是一个属性。

标签: php class methods extend


【解决方案1】:

正如已经评论过的,实际问题是您只设置了您在构造函数中定义的sqldate 属性,所以在实例化对象时设置一次。您在任何地方都没有对该属性进行更新。

可以进一步扩展派生类,以便每次修改都会更新sqldate 属性,但这很麻烦且容易出错。原因是该属性保留了需要同步的冗余信息。

在这种情况下使用格式化方法而不是同步属性要优雅得多:

<?php
define("br", "\n");

class testdate extends DateTime {
  public function getSqlDate() {
    return $this->format("Y.m.d");
  }
}

$td = new testdate("2020-08-23");
echo "       Today's Date: ".$td->format ("m/d/Y").br;
echo "   Today's SQL Date: ".$td->getSqlDate().br.br;
$td->modify ("+24 hour");
echo "    Tomorrow's Date: ".$td->format ("m/d/Y").br;
echo " Tomorrow Formatted: ".$td->format ("Y-m-d").br;
echo "  Tomorrow Sql Date: ".$td->getSqlDate().br.br;

明显的输出是:

       Today's Date: 08/23/2020
   Today's SQL Date: 2020.08.23

    Tomorrow's Date: 08/24/2020
 Tomorrow Formatted: 2020-08-24
  Tomorrow Sql Date: 2020.08.24

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-05-31
    • 2011-11-16
    • 1970-01-01
    • 2017-06-14
    • 2018-12-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多