PHP - Как я могу привести переменную к другой динамической переменной

У меня есть следующий код:

/**
 * Gets a property from an object.
 *
 * @param mixed $obj
 * @param string $property
 * @param null|string $type Convert value to another type. Optional.
 *
 * @return mixed|null Returns the property value or null if it does not exist.
 */
public static function getProperty($obj, $property, $type = null)
{
    if (!property_exists($obj, $property)) {
        return null;
    }

    if ($type === null) {
        return $obj->{$property};
    }

    // This does not work.. unfortunately
    return ({$type})$obj->{$property};
}

Но я не знаю, как я могу ввести последний возврат с переменной $type. Последний будет содержать что-то вроде «string» или «int», поэтому я могу преобразовать свойство в другой тип.


person TheKeymaster    schedule 17.01.2019    source источник