PHP - How can I type cast a variable by another dynamic variable

Viewed 61

I have the following code:

/**
 * 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};
}

But I do not know how I can type cast the last return with the $type variable. The last one would contain something like 'string' or 'int', so I am able to convert the property to another type.

0 Answers
Related