日期:2014-05-17  浏览次数:20445 次

怎么知道一个类实例有什么方法和属性?
怎么知道一个类实例有什么方法和属性?


------解决方案--------------------
例子 1. get_class_methods() 示例

<?php

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

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

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

$my_object = new myclass();

$class_methods = get_class_methods(get_class($my_object));

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

?>
 


运行结果: 


myclass
myfunc1
myfunc2
 

例子 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
 

------解决方案--------------------
搜索下php手册,里面有一个反射概念(reflection)

PHP code

<?php

class a
{
    public $abc = 'kkk';
    public function test() {
        echo $this->abc;
    }
    
    
}

//Instantiate the object
$b = new a();

//Instantiate the reflection object
$reflector = new ReflectionClass('a');

//Display the object properties
$properties = $reflector->getProperties();
foreach($properties as $property)
{
    echo "\$b->", $property->getName(), " => ", $b->{$property->getName()}, "\n";
}

//Display the object methods
$methods = $reflector->getMethods();
foreach($methods as $method)
{
    echo "\$b->", $method->getName(), " => ", $b->{$method->getName()}(), "\n";
}