gpt4 book ai didi

php - 可捕获的 fatal error : Object of class "" could not be converted to string in "" on line ""

转载 作者:行者123 更新时间:2023-12-02 17:40:37 26 4
gpt4 key购买 nike

我有这个代码:

class Date_Time{
private static $month;
private static $year;
private static $day;

public function Date_Time($format){
return self::getDate($format);
}

public static function getDate($date_format){
return self::replace_date_string($date_format);
}

public static function replace_date_string($string){
if(preg_match("/m/", $string)){
$string = preg_replace("/m/", self::getMonth(), $string);
}

if(preg_match("/Y/", $string)){
$string = preg_replace("/Y/", self::getYear(), $string);
}

return $string;
}

public static function getMonth(){
return date("m");
}

public static function getYear(){
return date("Y");
}
}

但是如果我这样打印它:

$date = new Date_Time("Y");
echo $date;

它给我一个错误提示:

Catchable fatal error: Object of class Date_Time could not be converted to string in index.php on line 2

我怎样才能解决这个问题,它不会给我一个错误,是什么导致了这个错误。

最佳答案

添加__toString()方法

public function __toString() {
return $this->getYear() .'-'. $this->getMonth() .'-'. $this->getDay();
}

当您尝试打印整个对象时需要此方法。

对于 PHP4:

public function toString() {
return $this->getYear() .'-'. $this->getMonth() .'-'. $this->getDay();
}

并手动调用此方法:

$date = new Date_Time("Y");
echo $date->toString();

关于php - 可捕获的 fatal error : Object of class "" could not be converted to string in "" on line "",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21218400/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com