/** * Cast a value to specific variable type. * * @static * * @param mixed $value Value to cast. * @param string $type Type to cast to. * @param bool $array2null (Optional) Whether to return null for arrays when casting to * bool, int, float, num or string. * If false, the individual values held in the array will recursively * be cast to the specified type. * Defaults to true. * @param bool $allow_empty (Optional) Whether to allow empty strings, empty arrays, empty objects. * If false, null will be returned instead of the empty string/array/object. * Defaults to true. * * @return mixed|null */ function cast($value, $type, $array2null = true, $allow_empty = true) { // Have the expected variables been passed ? if (isset($value) === false || isset($type) === false) { return null; } $type = strtolower(trim($type)); $valid_types = array('bool' => 1, 'boolean' => 1, 'int' => 1, 'integer' => 1, 'float' => 1, 'num' => 1, 'string' => 1, 'array' => 1, 'object' => 1); // Check if the typing passed is valid, if not return NULL. if (!isset($valid_types[$type])) { return null; } switch ($type) { case 'bool': case 'boolean': return CastToType::_bool($value, $array2null, $allow_empty); case 'integer': case 'int': return CastToType::_int($value, $array2null, $allow_empty); case 'float': return CastToType::_float($value, $array2null, $allow_empty); case 'num': if (is_numeric($value)) { $value = (double) $value != (int) $value ? (double) $value : (int) $value; } else { $value = null; } return $value; case 'string': return CastToType::_string($value, $array2null, $allow_empty); case 'array': return CastToType::_array($value, $allow_empty); case 'object': return CastToType::_object($value, $allow_empty); case 'null': default: return null; } }