Created
December 9, 2020 16:56
-
-
Save MushuLeDragon/b8c7aa80cd729b205434be5dcf314407 to your computer and use it in GitHub Desktop.
[PHP] Convert ObjectToArray or ArrayToObject class : https://likegeeks.com/convert-array-to-object-using-php/
This file contains 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 | |
namespace Src\App; | |
class ObjectConverterClass | |
{ | |
/** | |
* Convert Array to Object class | |
* | |
* @param array $array | |
* @param object $object | |
* @return object | |
*/ | |
public static function ArrayToObject(array $array, object $object): object | |
{ | |
$class = get_class($object); | |
$methods = get_class_methods($class); | |
foreach ($methods as $method) { | |
preg_match(' /^(set)(.*?)$/i', $method, $results); | |
$pre = $results[1] ?? ''; | |
$k = $results[2] ?? ''; | |
$k = strtolower(substr($k, 0, 1)) . substr($k, 1); | |
if ($pre == 'set' && !empty($array[$k])) { | |
$object->$method($array[$k]); | |
} | |
} | |
return $object; | |
} | |
/** | |
* Convert Object class to Array | |
* | |
* @param object $object | |
* @return array | |
*/ | |
public static function ObjectToArray(object $object): array | |
{ | |
$array = []; | |
$class = get_class($object); | |
$methods = get_class_methods($class); | |
foreach ($methods as $method) { | |
preg_match(' /^(get)(.*?)$/i', $method, $results); | |
$pre = $results[1] ?? ''; | |
$k = $results[2] ?? ''; | |
$k = strtolower(substr($k, 0, 1)) . substr($k, 1); | |
if ($pre == 'get') { | |
$array[$k] = $object->$method(); | |
} | |
} | |
return $array; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment