This article mainly introduces PHP to obtain classes through reflection and some basic applications. It has a certain reference value. Now I share it with you. Friends in need can refer to it.
In the past few days, Look at the core code of the laravel framework. Found extensive use of the reflection mechanism. Let’s take a brief look at some reflection applications
class A { private $_foo = 'this is a'; public function index() { return $this->_foo; } private function _come($param) { return 'this is come'.$param; } } $refClass = new ReflectionClass('A');//获得反射
Let’s use this reflection to get the private properties ofA
$privateParams = $refClass->getDefaultProperties(); print_r($privateParams);//得到结果 Array ( [_foo] => this is a ) echo $privateParams['_foo'];//得到 this is a
so that we can easily obtainA
's private attribute. So what should be done to execute private methods? Next, let's look at executing public methods first. Executing public methods is relatively simple.
/****************获得类的实例*******************/ $class = $refClass->newInstance(); echo $class->index();
This way you can call public methods. Let's look at the execution of the private method
/****************获取A的方法*******************/ $refHasClass = $refClass->getMethods(); print_r($refHasClass); /*** * Array ( [0] => ReflectionMethod Object ( [name] => index [class] => A ) * [1] => ReflectionMethod Object ( [name] => _come [class] => A ) ) */ $come = $refClass->getMethod('_come'); $come->setAccessible(true); echo $come->invoke($class,'this is param'); // this is athis is comethis is param
. First, you can get thecome
method throughgetMethod()
, and then set the accessibility of thecome
method. . Finally, execute the method throughinvoke
There are many available reflection methods, so I won’t go into them one by one here. If you are interested, you can take a look at the official documentation
The above is the entire content of this article. I hope it will be helpful to everyone's study. For more related content, please pay attention to the PHP Chinese website!
Related recommendations:
Notes on php-fpm parameter configuration of php7
The above is the detailed content of PHP uses reflection to obtain classes and some basic applications. For more information, please follow other related articles on the PHP Chinese website!