Php get public members

get_class_vars

Returns an associative array of declared properties visible from the current scope, with their default value. The resulting array elements are in the form of varname => value . In case of an error, it returns false .

Examples

Example #1 get_class_vars() example

var $var1 ; // this has no default value.
var $var2 = «xyz» ;
var $var3 = 100 ;
private $var4 ;

// constructor
function __construct () // change some properties
$this -> var1 = «foo» ;
$this -> var2 = «bar» ;
return true ;
>

$class_vars = get_class_vars ( get_class ( $my_class ));

foreach ( $class_vars as $name => $value ) echo » $name : $value \n» ;
>

The above example will output:

var1 : var2 : xyz var3 : 100

Example #2 get_class_vars() and scoping behaviour

function format ( $array )
return implode ( ‘|’ , array_keys ( $array )) . «\r\n» ;
>

class TestCase
public $a = 1 ;
protected $b = 2 ;
private $c = 3 ;

public static function expose ()
echo format ( get_class_vars ( __CLASS__ ));
>
>

TestCase :: expose ();
echo format ( get_class_vars ( ‘TestCase’ ));
?>

The above example will output:

// 5.0.0 a| * b| TestCase c a| * b| TestCase c // 5.0.1 - 5.0.2 a|b|c a|b|c // 5.0.3 + a|b|c a

See Also

User Contributed Notes 15 notes

If you want to retrieve the class vars from within the class itself, use $this.

var $a ;
var $b ;
var $c ;
var $d ;
var $e ;

function GetClassVars ()
return array_keys ( get_class_vars ( get_class ( $this ))); // $this
>

$class_vars = $Foo -> GetClassVars ();

foreach ( $class_vars as $cvar )
echo $cvar . «
\n» ;
>
?>

Produces, after PHP 4.2.0, the following:

All 3 of get_object_vars, get_class_vars and reflection getDefaultProperties will reveal the name of the array. For serialization I recommend:

$cName = get_class ( $this );
$varTemplate = get_class_vars ( $cName )
foreach ( $varTemplate as $name => $defaultVal ) <
$vars [ $name ] = $this -> $name ; // gets actual val.
>
?>

No scan the $vars and create serialization string how you wish.

This protects against erroneous prior deserializing in maintaining the integrity of the class template and ignoring unintended object properties.

I needed to get only the class static variables, leaving out instance variables.

function get_static_vars ( $class ) $result = array();
foreach ( get_class_vars ( $class ) as $name => $default )
if (isset( $class ::$ $name ))
$result [ $name ] = $default ;
return $result ;
>
?>

That function returns only the public ones. The same pattern can be used inside a class, then it returns private and protected static variables, too:

static protected function get_static_vars ( $class = NULL ) if (!isset( $class )) $class = get_called_class ();
$result = array();
foreach ( get_class_vars ( $class ) as $name => $default )
if (isset( $class ::$ $name ))
$result [ $name ] = $default ;
return $result ;
>
?>

So I wanted to get a list of the public parameters in a child class using a static function pre-5.3.0 (< 5.3.0). In 5.3.0+ you would use the new 'static' like you would 'self' to get the late binding.

class childClass extends parentClass
public $id ;
public $name ;

public static function getFields ()
return self :: _getFields ( __CLASS__ );
>

>
abstract class parentClass
public $idInParent ;
public $nameInParent ;

abstract public static function getFields ();

final protected static function _getFields ( $className )
$rtn = array();
foreach ( array_keys ( get_class_vars ( $className )) as $var ) $rtn [] = $var ;
>
return $rtn ;
>

var_dump ( childClass :: getFields ());
?>

Results:
array(4) [0]=>
string(2) «id»
[1]=>
string(4) «name»
[2]=>
string(10) «idInParent»
[3]=>
string(12) «nameInParent»
>

There seems to be be a function to get constants missing , i.e. get_class_constants() . so here is a simple function for you all. Hopefully Zend will include this in the next round as a native php call, without using reflection.

function GetClassConstants ( $sClassName ) $oClass = new ReflectionClass ( $sClassName );
return $oClass -> getConstants ());
>
?>

If you need get the child protected/private vars ignoring the parent vars, use like this:

class childClass extends parentClass private $login ;
private $password ;

public function __set ( $key , $val ) if ( $key == ‘password’ )
$this -> $key = md5 ( $val );
else
$this -> $key = $val ;
>
>
class parentClass public $name ;
public $email ;

function __construct () $reflection = new ReflectionClass ( $this );
$vars = array_keys ( $reflection -> getdefaultProperties ());
$reflection = new ReflectionClass ( __CLASS__ );
$parent_vars = array_keys ( $reflection -> getdefaultProperties ());

$my_child_vars = array();
foreach ( $vars as $key ) if (! in_array ( $key , $parent_vars )) $my_child_vars [] = $key ;
>
>

$child_class = new childClass ();
?>

If you assign a constant value using the self-scope by default to a variable, get_class_vars() will result in a FATAL error.

class Foo const Bar = «error» ;

print_r ( get_class_vars ( «Foo» ));

?>

. but using «Foo::Bar» instead «self::Bar» will work 😉

class someClass public function toArray () $records = array();

foreach( $this as $key => $value ) $records [ $key ] = $value ;
>

in PHP5 to get all the vars (including private etc.) use:

$reflection = new ReflectionClass($class);
$defaults = $reflection->getdefaultProperties();

I propse following for getting Public members, always:
if (! function_exists ( «get_public_class_vars» )) function get_public_class_vars ( $class ) return get_class_vars ( $class );
>
>
if (! function_exists ( «get_public_object_vars» )) function get_public_object_vars ( $object ) return get_object_vars ( $object );
>
>
?>

This is to mitigate the problem and a feature that get_object_vars($this) returns private members. Running it simply outside the scope will get the public.

Iterating public members only and their defaults are enormously useful in e.g. in serialization classes such as options where each public member is an serializable that is saved and loaded.

Contrary to multiple comments throughout the manual, get_class_vars() performed within a class can access any public, protected, and private members.

class Foo public $x ;
protected $y ;
private $z ;
public function __sleep () return( get_class_vars ( __CLASS__ ) );
>
>
?>

works fine (returns x, y, & z). However, given the same class as above,

print_r ( get_class_vars ( «Foo» ) );
?>

will NOT return x, y, & z. Instead it will only return the public members (in our case, z).

This is one of the best php functions. Look at what you can do

class Object
var $updtFields;//keep track of affected values
function Object($record=»») if (is_array($record))
$this->updtFields = array();
foreach(array_keys(get_class_vars(get_class($this))) as $k)
if (isset($record[$k]))
$this->$k = $record[$k];
$this->updtFields[] = $k;
>
>
>//end of arrayToObject

function toDebug($nl=’
‘)
foreach(array_keys(get_class_vars(get_class($this))) as $k)
echo «$k = [» . $this->$k . «]»;
>//end of toDebug
>

and you define your class like this
class Person extends Object var $name; //same same as in the form
var $phone;
>

when you submmit the form, you can get the data like

//everything in just one line,cool!! Also if you use pear db or adodb when you get data from the database you can do the same thing except use the $row that you get from the database. Remember to ask the result is associative mode.

This is my core Object for everthing I do and it works great.

get_class_vars_assoc()
— Returns an associative array with name of (parent) class(es) as key(s) and corresponding class vars as sub-arrays. My boilerplate for some crude O/R mapping.

Note: vars re-defined in sub-classes are ignored.

class GrandClass public $grandVar ;
public $in_grand_and_parent ;
public $in_grand_and_child ;

public static function load () print_r ( self :: get_class_vars_assoc ());
>

protected static function get_class_vars_assoc () $called = get_called_class ();
//echo «called: $called \n»;
$classVars [ $called ] = array_keys ( get_class_vars ( $called ));

$parent = get_parent_class ( $called );
while ( $parent !== FALSE ) //echo «parent: $parent \n»;
$classVars [ $parent ] = array_keys ( get_class_vars ( $parent ));
$classVars [ $called ] = array_diff ( $classVars [ $called ],
$classVars [ $parent ]);
if ( isset( $prevParentVars ) ) $prevParentVars = array_diff ( $prevParentVars ,
$classVars [ $parent ]);
>

$prevParentVars = & $classVars [ $parent ];
$parent = get_parent_class ( $parent );
>

class ParentClass extends GrandClass public $in_grand_and_parent ;
public $parentVar ;
public $in_parent_and_child ;
>

class ChildClass extends ParentClass public $in_grand_and_child ;
public $in_parent_and_child ;
public $childVar ;
>

[ParentClass] => Array
(
[1] => parentVar
[2] => in_parent_and_child
) [GrandClass] => Array
(
[0] => grandVar
[1] => in_grand_and_parent
[2] => in_grand_and_child
)

Источник

Get public properties that aren’t static with PHP Reflection

PHP has a Reflection API adds the ability to reverse-engineer classes, interfaces, functions, methods and extensions. I needed to use it to get all the publicly accessible properties for a class that aren’t static, but there doesn’t seem to be a way to get this «out of the box».

This post has my solution, but feel free to let me know a better way of doing it in the comments.

tl;dr

$reflection = new ReflectionClass($this); $public = $reflection->getProperties(ReflectionProperty::IS_PUBLIC); $static = $reflection->getProperties(ReflectionProperty::IS_STATIC); $properties = array_diff($public, $static);

$properties will now contain only the properties that are public and not static. If you are using namespaces, you’ll probably need to prefix ReflectionClass and ReflectionProperty with so they look like ReflectionClass and ReflectionProperty.

Longer answer

The following class «foo» has three public static properties (a, b, c) and three regular public properties (d, e, f). The «reflect» method echoes out all the public properties.

class foo < public static $a; public static $b; public static $c; public $d; public $e; public $f; public function reflect() < $reflection = new ReflectionClass($this); $properties = $reflection->getProperties(ReflectionProperty::IS_PUBLIC); foreach($properties as $property) < echo $property->name . "n"; > > >

Calling the «reflect» method liek this:

This includes the static properties, and I couldn’t work out any way to exclude them. Again, as noted at the top of this post, please feel free to let me know if there is a way to do it easily when calling the getProperties() method.

In order to get just the public properties that are not static, the only way I could see to do it was to get the IS_STATIC properties and use array_diff() to get only the public ones.

The revised class looks like this:

class foo < public static $a; public static $b; public static $c; public $d; public $e; public $f; public function reflect() < $reflection = new ReflectionClass($this); $public = $reflection->getProperties(ReflectionProperty::IS_PUBLIC); $static = $reflection->getProperties(ReflectionProperty::IS_STATIC); $properties = array_diff($public, $static); foreach($properties as $property) < echo $property->name . "n"; > > >

The output from reflect() now looks like this:

Is there a better way to do this? Please let me know in the comments section.

Источник

Читайте также:  What is css div class
Оцените статью