briannesbitt/Carbon · error · InvalidCastException

$className has not the instance() method needed to cast the

Error message

$className has not the instance() method needed to cast the date.

What it means

cast() converts the period into another representation by calling $className::instance($this); the only alternative path is a subclass of native DatePeriod, which is constructed directly from the period's raw values. A target class that neither defines a static instance() method nor extends DatePeriod cannot receive the cast, hence InvalidCastException (src/Carbon/CarbonPeriod.php:1626).

Source

Thrown at src/Carbon/CarbonPeriod.php:1626

     * Cast the current instance into the given class.
     *
     * @param string $className The $className::instance() method will be called to cast the current object.
     *
     * @return DatePeriod|object
     */
    public function cast(string $className): object
    {
        if (!method_exists($className, 'instance')) {
            if (is_a($className, DatePeriod::class, true)) {
                return new $className(
                    $this->rawDate($this->getStartDate()),
                    $this->getDateInterval(),
                    $this->getEndDate() ? $this->rawDate($this->getIncludedEndDate()) : $this->getRecurrences(),
                    $this->isStartExcluded() ? DatePeriod::EXCLUDE_START_DATE : 0,
                );
            }

            throw new InvalidCastException("$className has not the instance() method needed to cast the date.");
        }

        return $className::instance($this);
    }

    /**
     * Return native DatePeriod PHP object matching the current instance.
     *
     * @example
     * ```
     * var_dump(CarbonPeriod::create('2021-01-05', '2021-02-15')->toDatePeriod());
     * ```
     */
    public function toDatePeriod(): DatePeriod
    {
        return $this->cast(DatePeriod::class);
    }

View on GitHub (pinned to b13f05955d)

Solutions

  1. Cast to Carbon::class / CarbonImmutable::class / a subclass (they have instance())
  2. For native output use $period->toDatePeriod() (returns DatePeriod) or iterate ->toArray()
  3. Add a public static instance(self $period): static constructor to your target class

Example fix

// before
$native = $period->cast(\DateTimeImmutable::class); // InvalidCastException

// after
$native = $period->toDatePeriod(); // native DatePeriod of DateTimeImmutable
// or
$native = $period->cast(\Carbon\CarbonImmutable::class);
Defensive patterns

Strategy: type-guard

Type guard

/** @param class-string $class */
function canCastPeriod(string $class): bool
{
    return method_exists($class, 'instance') || is_a($class, DatePeriod::class, true);
}

$result = canCastPeriod($class) ? $period->cast($class) : $period->toDatePeriod();

Prevention

When it happens

Trigger: $period->cast(DateTime::class); $period->cast(DateTimeImmutable::class); $period->cast(SomeDto::class) — Carbon, CarbonImmutable and their subclasses work because they define instance().

Common situations: Trying to export a period to native PHP date objects; casting to a DTO/collection class for an API response; integrating with third-party period classes that have their own constructors.

Related errors


AI-assisted analysis of briannesbitt/Carbon@b13f05955d (2026-08-17). Data as JSON: /api/errors/69e78294600e0541. Report an issue: GitHub.