PHP Conference Japan 2024

get_class_vars

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

get_class_vars取得類別的預設屬性

描述

get_class_vars(string $class): array

取得指定類別的預設屬性。

參數

class

類別名稱

回傳值

回傳一個關聯陣列,其中包含從目前作用域可見的已宣告屬性及其預設值。結果陣列的元素形式為 varname => value。如果發生錯誤,則回傳 false

範例

範例 1 get_class_vars() 範例

<?php

class MyClass
{
public
$var1; // 這沒有明確的預設值(技術上它預設為 NULL)...
public $var2 = "xyz";
public
$var3 = 100;
private
$var4;

public function
__construct()
{
// 變更一些屬性
$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";
}

?>

以上範例將輸出

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

?>

以上範例將輸出

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

參見

新增註解

使用者貢獻的註解 15 則註解

rec at NOSPAM dot instantmassacre dot com
21 年前
如果想從類別內部擷取類別變數,請使用 $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";
}
?>

在 PHP 4.2.0 之後產生以下結果

a
b
c
d
e
ken at verango dot com
14 年前
get_object_vars、get_class_vars 和 reflection getDefaultProperties 這三個方法都會顯示陣列的名稱。對於序列化,我建議

<?php
$cName
= get_class($this);
$varTemplate= get_class_vars($cName)
foreach (
$varTemplate as $name => $defaultVal) {
$vars[$name] = $this->$name; // 取得實際值。
}
?>

掃描 $vars,並依照您的需求建立序列化字串。

這可以防止在維護類別範本的完整性並忽略非預期的物件屬性時,發生錯誤的預先還原序列化。
bof at bof dot de
12 年前
我需要只取得類別的靜態變數,而排除實例變數。

<?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;
}
?>

這個函式只會回傳公開 (public) 的靜態變數。同樣的模式可以在類別內部使用,那麼它也會回傳私有 (private) 和受保護 (protected) 的靜態變數。

<?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;
}
?>
artktec at art-k-tec dot com
17 年前
似乎缺少一個可以取得常數的函式,例如:get_class_constants() ... 所以這裡有一個簡單的函式給大家使用。希望 Zend 在下一版中可以將此作為原生 PHP 呼叫加入,而無需使用反射。

<?php
function GetClassConstants($sClassName) {
$oClass = new ReflectionClass($sClassName);
return
$oClass->getConstants());
}
?>
flobee
9 年前
<?php
class someClass {
public function
toArray() {
$records = array();

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

return
$records;
}

}
?>
ciantic
12 年前
我建議以下方法來取得公開 (Public) 成員,總是如此
<?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);
}
}
?>

這是為了緩解 get_object_vars($this) 會回傳私有成員的問題。在範圍外簡單地執行它將會取得公開的成員。

僅迭代公開成員及其預設值在例如序列化類別中非常有用,例如選項,其中每個公開成員都是可以儲存和載入的可序列化項目。
ianitsky at gmail dot com
15 年前
如果您需要取得子類別的受保護/私有變數,並忽略父類別的變數,請使用以下方式

<?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
15 年前
因此,我想在使用靜態函式 pre-5.3.0 (< 5.3.0) 的情況下,取得子類別中公開參數的清單。在 5.3.0+ 中,您可以使用新的 'static',就像使用 'self' 來取得延遲綁定一樣。

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

結果
array(4) {
[0]=>
string(2) "id"
[1]=>
string(4) "name"
[2]=>
string(10) "idInParent"
[3]=>
string(12) "nameInParent"
}
bernd at tiggerswelt dot net
17 年前
如果您預設使用 self 範圍將常數值指派給變數,get_class_vars() 將會導致致命錯誤。

範例

<?PHP

class Foo {
const
Bar = "error";

public
$Foo = self::Bar;
}

print_r(get_class_vars("Foo"));

?>

... 但是使用 "Foo::Bar" 而不是 "self::Bar" 就可以正常運作 ;)
alan_k at php dot net
19 年前
在 PHP5 中取得所有變數(包括私有等),請使用

$reflection = new ReflectionClass($class);
$defaults = $reflection->getdefaultProperties();
php dot net at sharpdreams dot com
19 年前
與手冊中許多註解相反,在類別內執行的 get_class_vars() 可以存取任何公開、受保護和私有的成員。

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

運作良好 (回傳 x、y 和 z)。然而,如果給定與上述相同的類別,

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

將不會回傳 x、y 和 z。相反地,它只會回傳公開成員(在我們的例子中是 z)。
phpnet at stccorp dot net
17 年前
這是最好的 PHP 函式之一。看看你可以做什麼

class Object
{
var $updtFields;//記錄受影響的值
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
}

現在你可以做一些非常酷的事情。如果你有一個像這樣的表單
<form action="" method="post">
<input type="text" name="name" />
<input type="text" name="phone" />
<input type="submit" />
</form>

然後你像這樣定義你的類別
class Person extends Object{
var $name; //跟表單中的名稱相同
var $phone;
}

當您提交表單時,您可以像這樣取得資料

$person = new Person($_POST);

//所有事情都只需一行程式碼,超棒!! 此外,如果您使用 pear db 或 adodb 從資料庫取得資料,您也可以做相同的事情,只是改用從資料庫取得的 $row。請記得要求結果為關聯模式。

這是我所有操作的核心物件,而且它運作良好。
Mattias Ahlbck
12 年前
get_class_vars_assoc()
- 返回一個關聯陣列,其中 (父) 類別的名稱作為鍵,而對應的類別變數作為子陣列。這是我的粗糙 O/R 對應的樣板程式碼。

注意:在子類別中重新定義的變數會被忽略。

<?php

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);
}

return
$classVars;
}
}

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;
}

ChildClass::load();

?>

陣列
(
[ChildClass] => 陣列
(
[2] => childVar
)

[ParentClass] => 陣列
(
[1] => parentVar
[2] => in_parent_and_child
)

[GrandClass] => 陣列
(
[0] => grandVar
[1] => in_grand_and_parent
[2] => in_grand_and_child
)

)
pBakhuis at Gmail dot com
13 年前
如果您需要在包含類別之前取得變數,這個函式似乎無法運作。
使用反射類別來解決這個問題。
https://php.dev.org.tw/reflectionclass
gizmobits at hotmail dot com
18 年前
我想要一個簡單的 ToString() 函式,它是自動的且獨立於類別。我想要將它轉儲到多個類別中的任何一個,並快速取得值。我想將它留在那裡,以便我可以為每個類別自訂它,所以外部函式不適合。我提出了這個想法,並認為它可能很有用。玩得開心!

<?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;
}

?>
To Top