PHP的反射机制

在面向对象中最经典的使用就是反射,之前在Java语言中,使用反射可以解耦,用于依赖注入。

在PHP中,同样也有如此强大的地方,我们利用反射来获取一个对象的实例。

首先我们先写一个类:

 1 class TestClass{
 2     private $number;
 3     private $name;
 4 
 5     public function __construct(){
 6         $this->number=123;
 7         $this->name="test";
 8     }
 9 
10     public function printstu_info(){
11         echo "the student number is {$this->number},and name is {$this->name}";
12     }
13 }

在PHP中可以使用ReflectionClass类来获取这个类的详细情况。在调用其newInstance方法可以获取这个类的实例。

使用这样就可以获取类的实例,和new的效果会是一样的。

1 prod_class=new ReflectionClass('TestClass');
2 $instance=$prod_class->newInstance();
3 $instance->printstu_info();

这个程序的输出为the student number is 123,and name is test

一般情况下我们可以使用如下方式:

1 $test=new TestClass();
2 $test->printstu_info();
原文地址:https://www.cnblogs.com/Summer7C/p/5551533.html