get_class_vars

(PHP 4, PHP 5)

get_class_vars --  返回由类的默认属性组成的数组

描述

array get_class_vars ( string class_name )

返回由类的默认属性组成的关联数组,此数组的元素以 varname => value 的形式存在。

注: 在 PHP 4.2.0 之前,get_class_vars() 不会包含未初始化的类变量。

例子 1. get_class_vars() 示例

<?php

class myclass {

    var
$var1; // 此变量没有默认值……
    
var $var2 = "xyz";
    var
$var3 = 100;
    
    
// constructor
    
function myclass() {
        return(
TRUE);
    }

}

$my_class = new myclass();

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

foreach (
$class_vars as $name => $value) {
    echo
"$name : $value\n";
}

?>

运行结果:

// 在 PHP 4.2.0 之前
var2 : xyz
var3 : 100

// 从 PHP 4.2.0 开始
var1 :
var2 : xyz
var3 : 100

参见 get_class_methods()get_object_vars()


add a note add a note User Contributed Notes
gizmobits at hotmail dot com
04-Mar-2006 11:48
I wanted a simple ToString() function that was automatic and class independent.  I wanted to dump it into any of several classes and get values quickly.  I wanted to leave it there so I could customize it for each class, so an outside function wasn't suitable.  I came up with this and thought it might be useful.  Have fun!

<?php
 
function ToString () {
  
$s = "";
  
$s .= "<table>\n";
  
$s .= "<tr><td colspan=2><hr></td></tr>\n";
   foreach (
get_class_vars(get_class($this)) as $name => $value) {
    
$s .= "<tr><td>$name:</td><td>" . $this->$name . "</td></tr>\n";
   }
  
$s .= "<tr><td colspan=2><hr></td></tr>\n";
  
$s .= "</table>\n";
   return
$s;
  }

?>
php dot net at sharpdreams dot com
25-Oct-2005 09:25
Contrary to multiple comments throughout the manual, get_class_vars() performed within a class can access any public, protected, and private members.

<?php
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,

<?php
print_r
( get_class_vars( "Foo" ) );
?>

will NOT return x, y, & z. Instead it will only return the public members (in our case, z).
alan_k at php dot net
22-Jan-2005 11:23
in PHP5 to get all the vars (including private etc.) use:

$reflection = new ReflectionClass($class);
$defaults = $reflection->getdefaultProperties();
rec at NOSPAM dot instantmassacre dot com
24-Jan-2003 08:23
If you want to retrieve the class vars from within the class itself, use $this.

<?php
class Foo {

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

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

}

$Foo = new Foo;

$class_vars = $Foo->GetClassVars();

foreach (
$class_vars as $cvar)
{
   echo
$cvar . "<br />\n";
}
?>

Produces, after PHP 4.2.0, the following:

a
b
c
d
e