{"record":{"id":"69e78294600e0541","repo":"briannesbitt/Carbon","slug":"classname-has-not-the-instance-method-needed-to","errorCode":null,"errorMessage":"$className has not the instance() method needed to cast the date.","messagePattern":"\\$className has not the instance\\(\\) method needed to cast the date\\.","errorType":"exception","errorClass":"InvalidCastException","httpStatus":null,"severity":"error","filePath":"src/Carbon/CarbonPeriod.php","lineNumber":1626,"sourceCode":"     * Cast the current instance into the given class.\n     *\n     * @param string $className The $className::instance() method will be called to cast the current object.\n     *\n     * @return DatePeriod|object\n     */\n    public function cast(string $className): object\n    {\n        if (!method_exists($className, 'instance')) {\n            if (is_a($className, DatePeriod::class, true)) {\n                return new $className(\n                    $this->rawDate($this->getStartDate()),\n                    $this->getDateInterval(),\n                    $this->getEndDate() ? $this->rawDate($this->getIncludedEndDate()) : $this->getRecurrences(),\n                    $this->isStartExcluded() ? DatePeriod::EXCLUDE_START_DATE : 0,\n                );\n            }\n\n            throw new InvalidCastException(\"$className has not the instance() method needed to cast the date.\");\n        }\n\n        return $className::instance($this);\n    }\n\n    /**\n     * Return native DatePeriod PHP object matching the current instance.\n     *\n     * @example\n     * ```\n     * var_dump(CarbonPeriod::create('2021-01-05', '2021-02-15')->toDatePeriod());\n     * ```\n     */\n    public function toDatePeriod(): DatePeriod\n    {\n        return $this->cast(DatePeriod::class);\n    }\n","sourceCodeStart":1608,"sourceCodeEnd":1644,"githubUrl":"https://github.com/briannesbitt/Carbon/blob/b13f05955dcfd7da71d60af745fd148cbdb73505/src/Carbon/CarbonPeriod.php#L1608-L1644","documentation":"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).","triggerScenarios":"$period->cast(DateTime::class); $period->cast(DateTimeImmutable::class); $period->cast(SomeDto::class) — Carbon, CarbonImmutable and their subclasses work because they define instance().","commonSituations":"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.","solutions":["Cast to Carbon::class / CarbonImmutable::class / a subclass (they have instance())","For native output use $period->toDatePeriod() (returns DatePeriod) or iterate ->toArray()","Add a public static instance(self $period): static constructor to your target class"],"exampleFix":"// before\n$native = $period->cast(\\DateTimeImmutable::class); // InvalidCastException\n\n// after\n$native = $period->toDatePeriod(); // native DatePeriod of DateTimeImmutable\n// or\n$native = $period->cast(\\Carbon\\CarbonImmutable::class);","handlingStrategy":"type-guard","validationCode":null,"typeGuard":"/** @param class-string $class */\nfunction canCastPeriod(string $class): bool\n{\n    return method_exists($class, 'instance') || is_a($class, DatePeriod::class, true);\n}\n\n$result = canCastPeriod($class) ? $period->cast($class) : $period->toDatePeriod();","tryCatchPattern":null,"preventionTips":["Cast only to Carbon/CarbonImmutable subclasses, or classes where you added static instance()","Use toDatePeriod() for native output instead of casting to DateTime classes","Document cast targets in one place rather than accepting arbitrary class names from callers"],"tags":["carbon","carbon-period","cast","type-conversion"],"backgroundTag":"invalid-cast-target","analyzedSha":"b13f05955dcfd7da71d60af745fd148cbdb73505","analyzedAt":"2026-08-17T04:40:56.953Z","schemaVersion":2},"datasetVersion":"2026-08-17T09:17:11.063Z"}