Home >Backend Development >PHP Tutorial > 如何知道一个类实例有什么方法和属性

如何知道一个类实例有什么方法和属性

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOriginal
2016-06-13 13:12:45798browse

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


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


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() 示例


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";
} <div class="clear">
                 
              
              
        
            </div>
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn