[PHP] Convert class member variable to array


Writing time : 2017-12-28 01:17:31

Convert class member variable to array

get_object_vars


If the class member is public, you can convert the class member to an array using the get_object_vars method.

class PublicTestClass  
{  
public $foo = "aaa";  
public $bar = "bbb";  
}  
  
$publicTestClass = new PublicTestClass();  
var_dump(get_object_vars($publicTestClass));  

Output result

array(2) { ["foo"]=> string(3) "aaa" ["bar"]=> string(3) "bbb" }  

If the class member is private, it is not stored in the array even if the get_object_vars method is used.

class PrivateTestClass  
{  
private $foo = "aaa";  
private $bar = "bbb";  
}  
  
$privateTestClass = new PrivateTestClass();  
var_dump(get_object_vars($privateTestClass));  

Output result

array(0) { }  

reflection


Private class members can also be converted to arrays by using reflection instead of get_object_vars.

class PrivateTestClass  
{  
private $foo = "aaa";  
private $bar = "bbb";  
}  
  
$reflectionClass = new ReflectionClass('PrivateTestClass');  
  
// private 클래스 멤버 정보를 저장 배열 생성  
$members = array();  
  
// property 목록을 받아온다.  
$properties = $reflectionClass->getProperties();  
foreach($properties as $property){  
// setAccessible 메소드를 호출해서 private property access  
$reflectionProperty = $reflectionClass->getProperty($property->name);  
$reflectionProperty->setAccessible(true);  
  
// private 멤버에 저장된 값을 가져온다.  
$value = $reflectionProperty->getValue($privateTestClass);  
  
// 배열에 저장한다.  
$members[$property->name] = $value;  
}  
  
// 벼열 결과 출력  
var_dump($members);  

Output result

array(2) { ["foo"]=> string(3) "aaa" ["bar"]=> string(3) "bbb" }  

Reference URL


http://php.net/manual/en/function.get-object-vars.php http:/ /php.net/manual/en/class.reflectionclass.php http://php.net/manual/en/reflectionproperty.getvalue .php https://stackoverflow.com/questions/31297230/php-get-object-vars-cant-access-private-properties -in-child-object

Previous post