PHP get_class_vars() Function
The PHP get_class_vars() function is used to get the default properties of the given class.
Syntax
get_class_vars(class)
Parameters
class |
Required. Specify the class name. |
Return Value
Returns an associative array of declared properties visible from the current scope, with their default value. The returned array contains elements in the form of variable_name => variable_value. In case of an error, it returns false.
Example: get_class_vars() example
The example below shows the usage of get_class_vars() function.
<?php class myClass { var $var1; //no default value var $var2 = "xyz"; var $var3 = 100; private $var4 = 500; //class constructor function __construct() { //change some properties $this->var1 = "foo"; $this->var2 = "bar"; return true; } } //getting the default properties print_r(get_class_vars('myclass')); ?>
The output of the above code will be:
Array ( [var1] => [var2] => xyz [var3] => 100 )
Example: using with derived class
Consider the example below where this function is used with a derived class.
<?php class myClass { var $var1 = "xyz"; var $var2 = 100; private $var3 = 500; //class constructor function __construct() { //codes } } class newClass extends myClass { var $var4 = 1000; private $var5 = 5000; } //getting the default properties of newClass print_r(get_class_vars('newClass')); ?>
The output of the above code will be:
Array ( [var4] => 1000 [var1] => xyz [var2] => 100 )
Example: get_class_vars() and scoping behavior
Consider one more example which illustrates on scoping behavior while using this function.
<?php 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 output of the above code will be:
a|b|c a
❮ PHP Classes/Objects Reference