downloads | documentation | faq | getting help | mailing lists | licenses | wiki | reporting bugs | php.net sites | links | conferences | my php.net

search for in the

get_class> <get_class_methods
Last updated: Fri, 14 Aug 2009

view this page in

get_class_vars

(PHP 4, PHP 5)

get_class_varsRetourne les valeurs par défaut des propriétés d'une classe

Description

array get_class_vars ( string $class_name )

Retourne les valeurs par défaut des propriétés d'une classe.

Liste de paramètres

class_name

Le nom de la classe

Valeurs de retour

retourne un tableau contenant les valeurs par défaut des propriétés publiques de la classe class_name . Les éléments du tableau résultant sont sous la forme : nom_variable => valeur.

Historique

Version Description
5.0.3 En fonction du contexte, get_class_vars() ne retourne que les propriétés qui sont accessibles depuis ce contexte.
5.0.2 Appeler get_class_vars() produit toutes les propriétés sous la forme d'un tableau, contrairement au comportement précédent où les propriétés privées et publiques étaient préfixées par des caractères null.
5.0.1 Appeler get_class_vars() retourne toutes les propriétés, exactement comme convertir un objet en un tableau.
Avant la version 4.2.0 Les variables de classe non initialisées n'étaient pas rapportées par get_class_vars().

Exemples

Exemple #1 Exemple avec get_class_vars()

<?php

class myclass {

    var 
$var1// pas de valeur par défaut...
    
var $var2 "xyz";
    var 
$var3 100;
    private 
$var4// PHP 5

    // constructeur
    
function myclass() {
        
// changement de quelques propriétés
        
$this->var1 "foo";
        
$this->var2 "bar";
        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";
}

?>

L'exemple ci-dessus va afficher :

// Avant PHP 4.2.0
var2 : xyz
var3 : 100

// Depuis PHP 4.2.0
var1 :
var2 : xyz
var3 : 100

Exemple #2 Exemple avec get_class_vars() et les contextes

<?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'));
?>

L'exemple ci-dessus va afficher :

// 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

Voir aussi



get_class> <get_class_methods
Last updated: Fri, 14 Aug 2009
 
add a note add a note User Contributed Notes
get_class_vars
ianitsky at gmail dot com
10-Nov-2009 07:53
If you need get the child protected/private vars ignoring the parent vars, use like this:

<?php
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;
            }
        }
       
       
print_r($my_child_vars);
    }
}

$child_class = new childClass();
?>
harmor
20-Dec-2008 11:53
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.

<?php
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"
}
artktec at art-k-tec dot com
16-Nov-2007 05:18
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.

<?php
  
function GetClassConstants($sClassName) {
     
$oClass = new ReflectionClass($sClassName);
      return
$oClass->getConstants());
   }
?>
phpnet at stccorp dot net
15-Jun-2007 12:18
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='<br>')
   {
       foreach(array_keys(get_class_vars(get_class($this))) as $k)
       echo "$k = [" . $this->$k . "]{$nl}";
    }//end of toDebug 
}

Now you can do really cool things. If you have a form like
<form action="" method="post">
  <input type="text" name="name" />
  <input type="text" name="phone" />
  <input type="submit" />
</form>

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

$person = new Person($_POST);

//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.
bernd at tiggerswelt dot net
29-Jan-2007 10:52
If you assign a constant value using the self-scope by default to a variable, get_class_vars() will result in a FATAL error.

Example:

<?PHP

 
class Foo {
    const
Bar = "error";
   
    public
$Foo = self::Bar;
  }
 
 
print_r(get_class_vars("Foo"));

?>

... but using "Foo::Bar" instead "self::Bar" will work ;)
gizmobits at hotmail dot com
04-Mar-2006 03: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 01: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 03: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 12: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

get_class> <get_class_methods
Last updated: Fri, 14 Aug 2009
 
 
show source | credits | stats | sitemap | contact | advertising | mirror sites