Home > Enterprise >  Extending DateTimeImmutable calling __construct and __format
Extending DateTimeImmutable calling __construct and __format

Time:11-03

I'm trying to use methods from the DateTimeImmutable class in my own class.

I don't understand why return parent::format('Y-m-d H:i') doesn't return a string 2022-10-01 15:38, in the documentation it looks like it should: https://www.php.net/manual/en/class.datetimeimmutable.php public format(string $format): string.

Why does it not return a string?

<?php

class CastsDateTime extends DateTimeImmutable
{
    public function __construct(string $date)
    {
        parent::__construct($date);
        return parent::format('Y-m-d H:i');
    }
}

$date = new CastsDateTime('2022-10-01T15:38');

var_export($date); /* returns 
CastsDateTime::__set_state(array(
   'date' => '2022-10-01 15:38:00.000000',
   'timezone_type' => 3,
   'timezone' => 'UTC',
)) */

Final Solution

class CastsDateTime extends DateTimeImmutable
{
    // public function __construct(string $date)
    public function __invoke()
    {
        // parent::__construct($date);
        return parent::format('Y-m-d H:i');
    }
}

echo (new CastsDateTime('2022-10-01T15:38'))();
// $date = new CastsDateTime('2022-10-01T15:38');
// var_export($date);
/* returns 
CastsDateTime::__set_state(array(
   'date' => '2022-10-01 15:38:00.000000',
   'timezone_type' => 3,
   'timezone' => 'UTC',
)) */

CodePudding user response:

The constructor of a class has no return value. If you need a special formatting method, give that method a new name. Overriding the methods of the parent class is not a good idea. In this case, you don't need a constructor either.

Example:

class CastsDateTime extends DateTimeImmutable
{
    public function myFormat()
    {
        return parent::format('Y-m-d H:i');
    }
}
$dt = new CastsDateTime();
echo $dt->myFormat();

Demo: https://3v4l.org/tQ87q

With your extension CastsDateTime you can of course also use all methods of the parent class.

  • Related