Skip to content
PHP Logo

What is the difference between upcast and downcast in PHP, and why is it not feasible to cast a base class object to a derived class object?

In PHP, upcasting involves casting a derived class object to a base class object, while downcasting involves casting a base class object to a derived class object. It is not feasible to cast a base class object to a derived class object because the base class object does not have the properties or methods of the derived class, so attempting to cast it would result in a fatal error. To solve this issue, you should create a new instance of the derived class and manually copy over the properties from the base class object.

php
class BaseClass {
    public $property = 'Base Property';
}

class DerivedClass extends BaseClass {
    public $newProperty = 'Derived Property';
}

$baseObj = new BaseClass();
$derivedObj = new DerivedClass();

// Upcasting (Derived to Base)
$upcastedObj = $derivedObj;

// Downcasting (Base to Derived)
$downcastedObj = new DerivedClass();
$downcastedObj->property = $baseObj->property;