php反射函數

來源:互聯網
上載者:User
最常用的幾個個php反射函數 get_class get_class_methods

1. get_class ? 返回對象的類名

string get_class ([ object $obj ] )

返回對象執行個體 obj 所屬類的名字。如果 obj 不是一個對象則返回 FALSE。

Note: 在 PHP 擴充庫中定義的類返回其原始定義的名字。在 PHP 4 中 get_class() 返回使用者定義的類名的小寫形式,但是在 PHP 5 中將返回類名定義時的名字,如同擴充庫中的類名一樣。

Note: 自 PHP 5 起,如果在對象的方法中調用則 obj 為可選項。

Example#1 使用 get_class()


class foo {
function foo()
{
// implements some logic
}

function name()
{
echo "My name is " , get_class($this) , "/n";
}
}

// create an object
$bar = new foo();

// external call
echo "Its name is " , get_class($bar) , "/n";

// internal call
$bar->name();

?>

上例將輸出:

Its name is foo My name is foo
 
2.get_class_methods ? 返回由類的方法名組成的數組
說明

array get_class_methods ( mixed $class_name )

返回由 class_name 指定的類中定義的方法名所組成的數組。如果出錯,則返回 NULL。

Example#1 get_class_methods() 樣本


class myclass {
// constructor
function myclass()
{
return(true);
}

// method 1
function myfunc1()
{
return(true);
}

// method 2
function myfunc2()
{
return(true);
}
}

$class_methods = get_class_methods('myclass');
// or
$class_methods = get_class_methods(new myclass());

foreach ($class_methods as $method_name) {
echo "$method_name/n";
}

?>

上例將輸出:

myclass myfunc1 myfunc2 

3.

get_class_vars ? 返回由類的預設屬性組成的數組

說明

array get_class_vars ( string $class_name )

返回由類的預設公有屬性群組成的關聯陣列,此數組的元素以 varname => value 的形式存在。

Note: 在 PHP 4.2.0 之前,get_class_vars() 不會包含未初始化的類變數。

Example#1 get_class_vars() 樣本


class myclass {

var $var1; // 此變數沒有預設值……
var $var2 = "xyz";
var $var3 = 100;
private $var4; // PHP 5

// constructor
function myclass() {
// 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 : $value/n";
}

?>

上例將輸出:

// 在 PHP 4.2.0 之前 var2 : xyz var3 : 100 // 從 PHP 4.2.0 開始 var1 : var2 : xyz var3 : 100 

 
  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.