PHP-如何通过其他动态变量键入类型转换变量

时间:2019-01-17 14:18:31

标签: php casting typing

我有以下代码:

/**
 * 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变量来键入最后的返回值。最后一个将包含“字符串”或“整数”之类的内容,因此我可以将属性转换为另一种类型。

0 个答案:

没有答案
相关问题