Is it possible to cast a parent class to its child in PHP? If not, what is the most efficient alternative to effecting this?
For example, the following results in an error:
<?php
class Foo {
public $test;
public static function create(): self {
$a = new self();
$a->test = 123;
return $a;
}
}
class Bar extends Foo {
public $baz;
public static function create(): self {
$b = (self) parent::create(); // <--- Is this possible?
$b->baz = 456;
return $b;
}
}
$bar = Bar::create();
var_dump($bar); /* should output:
object(Bar)[35]
public 'baz' => int 456
public 'test' => int 123 */