Created
May 27, 2018 10:28
-
-
Save dajve/35a99d170683bb2221abae3dc80d7f71 to your computer and use it in GitHub Desktop.
PHP Object To Array
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 | |
class Foo | |
{ | |
/**#@+ | |
* @var string | |
*/ | |
public $hello = "Hello"; | |
protected $world = "World"; | |
private $exclam = "!"; | |
/**#@-*/ | |
/** | |
* @return string | |
*/ | |
public function getHello() | |
{ | |
return $this->hello; | |
} | |
/** | |
* @return string | |
*/ | |
public function getWorld() | |
{ | |
return $this->world; | |
} | |
/** | |
* @return string | |
*/ | |
public function getExclam() | |
{ | |
return $this->exclam; | |
} | |
/** | |
* @return string[] | |
*/ | |
public function asArray() | |
{ | |
return [ | |
'hello' => $this->getHello(), | |
'world' => $this->getWorld(), | |
'exclam' => $this->getExclam(), | |
]; | |
} | |
} | |
$foo = new Foo(); | |
print_r($foo); | |
// Foo Object | |
// ( | |
// [hello] => Hello | |
// [world:protected] => World | |
// [exclam:Foo:private] => ! | |
// ) | |
print_r($foo->asArray()); | |
// Array | |
// ( | |
// [hello] => Hello | |
// [world] => World | |
// [exclam] => ! | |
// ) | |
// https://www.vitallogic.co.uk/convert-php-object-to-associative-array/ | |
// Solution 1 – Using json_decode & json_encode | |
print_r(json_decode(json_encode($foo), true)); | |
// Array | |
// ( | |
// [hello] => Hello | |
// ) | |
// Solution 2 – Type Casting object to an array | |
print_r((array)$foo); | |
// Array | |
// ( | |
// [hello] => Hello | |
// [*world] => World | |
// [Fooexclam] => ! | |
// ) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment