是否可以通过静态方法调用实例方法? 这是我的代码。
class MyDateTime extends DateTime
{
public static function mysqlToHuman($date)
{
return $this->format('d-m-Y');
}
public static function humanToMysql($date)
{
return $this->format('Y-m-d');
}
}
echo MyDateTime::mysqlToHuman('2013-12-01');
我得到了
Fatal error: Non-static method DateTime::format() cannot be called statically
如果没有如何达到如上所述的预期效果?
答案 0 :(得分:3)
class MyDateTime extends \DateTime
{
private static function getInstance()
{
static $instance;
if (!$instance instanceof static) {
$instance = new static();
}
return $instance;
}
public static function mysqlToHuman($date)
{
return static::getInstance()->format('d-m-Y');
}
public static function humanToMysql($date)
{
return static::getInstance()->format('Y-m-d');
}
}
echo MyDateTime::mysqlToHuman('2013-12-01');
答案 1 :(得分:1)
您只需从结果中创建日期对象:
$date = new \Datetime('2013-12-01');
echo $date->format('d-m-Y'); // 01-12-2013
或者如果你需要一个带静态方法的辅助类:
$formatted = DateFormatter::mysqlToHuman($date);
echo $formatted; // 01-12-2013 - however you like.
如果只添加静态方法,则扩展类没有意义。