PHP.mk документација

get_class_vars

Почист и полокален преглед на PHP референцата, со задржана структура од PHP.net и подобра читливост за примери, секции и белешки.

function.get-class-vars.php PHP.net прокси Преводот се освежува
Оригинал на PHP.net
Патека function.get-class-vars.php Локална патека за оваа страница.
Извор php.net/manual/en Оригиналниот HTML се реупотребува и локално се стилизира.
Режим Прокси + превод во позадина Кодовите, табелите и белешките остануваат читливи во истиот тек.
get_class_vars

Референца за `function.get-class-vars.php` со подобрена типографија и навигација.

function.get-class-vars.php

get_class_vars

(PHP 4, PHP 5, PHP 7, PHP 8)

get_class_varsЗеми ги стандардните својства на класата

= NULL

get_class_vars(string $class): array

Земи ги стандардните својства на дадената класа.

Параметри

class

Име на класата

Вратени вредности

Враќа асоцијативен низ од декларирани својства видливи од тековниот опсег, со нивната стандардна вредност. Елементите на низот се во форма на varname => value. Во случај на грешка, враќа false.

Примери

Пример #1 get_class_vars() example

<?php

class MyClass
{
public
$var1; // This has no explicit default value (technically it has NULL as a default)...
public $var2 = "xyz";
public
$var3 = 100;
private
$var4;

public function
__construct()
{
// Change some properties
$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}: ", var_export($value, true), "\n";
}

?>

Пример #1 Пример што покажува затворачка ознака што го опфаќа последниот нов ред

var1: NULL
var2: 'xyz'
var3: 100

Пример #2 get_class_vars() и однесување на опсегот

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

?>

Пример #1 Пример што покажува затворачка ознака што го опфаќа последниот нов ред

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

Види Исто така

  • get_class_methods() - Ги добива имињата на методите на класата
  • get_object_vars() - Ги добива својствата на дадениот објект

Белешки од корисници Управување со PDO конекции

rec at NOSPAM dot instantmassacre dot com
пред 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
bof at bof dot de
пред 13 години
I needed to get only the class static variables, leaving out instance variables.

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

<?php
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;
}
?>
ken at verango dot com
пред 15 години
All 3 of get_object_vars, get_class_vars and reflection getDefaultProperties will reveal the name of the array.  For serialization I recommend:

<?php
$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.
flobee
пред 10 години
<?php 
class someClass {
    public function toArray() {
        $records = array();

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

        return $records;
    }

}
?>
ciantic
пред 14 години
I propse following for getting Public members, always:
<?PHP
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.
ianitsky at gmail dot com
пред 16 години
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();
?>
artktec at art-k-tec dot com
пред 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());
   }
?>
На оваа страница

Автоматски outline од активната документација.

Насловите ќе се појават тука по вчитување.

Попрегледно читање

Примерите, changelog табелите и user notes се визуелно издвоени за да не се губат во долгата содржина.

Брз совет Користи го outline-от Скокни директно на главните секции од активната страница.
Извор Оригиналниот линк останува достапен Кога ти треба целосен upstream context, отвори го PHP.net во нов tab.