Last active
August 18, 2021 23:55
-
-
Save NewEXE/7d3b89c49f059fd339dcb8177e204612 to your computer and use it in GitHub Desktop.
Convert anything to string (PHP)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* @param mixed $value Value of any PHP type. | |
* @return string Value as readable string. | |
*/ | |
function toString($value, $compactArray = true): string | |
{ | |
$data_type = ''; | |
if (is_array($value)) { | |
if ($compactArray) { | |
$value = json_encode($value); | |
} else { | |
$value = print_r($value, true); | |
} | |
} elseif (is_object($value)) { | |
$data_type .= get_class($value); | |
if ($value instanceof \Exception) { | |
$data_type .= ': Exception'; | |
$value = print_r([ | |
'message' => $value->getMessage(), | |
'code' => $value->getCode(), | |
'file' => $value->getFile(), | |
'line' => $value->getLine(), | |
'trace' => $value->getTraceAsString() | |
], true); | |
} else { | |
$value = print_r($value, true); | |
} | |
} elseif (is_resource($value)) { | |
$data_type .= get_resource_type($value); | |
$value = (string) $value; | |
} elseif (is_bool($value)) { | |
$value = $value ? 'true' : 'false'; | |
} elseif ($value === null) { | |
$value = 'NULL'; | |
} elseif (!settype($value, 'string')) { | |
$value = 'Error: can\'t convert input data to string'; | |
} | |
if (!empty($data_type)) { | |
$value = '[' . $data_type . '] ' . $value; | |
} | |
return $value; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment