This article mainly introduces about PHP through reflection to get the class and some basic applications, has a certain reference value, now share to everyone, the need for friends can refer to
These days are looking at the core code of the Laravel framework. The reflection mechanism was found to be used extensively. Here's a quick look at some reflective 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 ');//Get Reflection
Let's take this reflection to get A
the private property
$privateParams = $refClass->getdefaultproperties ();p rint_r ($privateParams);//Get result Array ([_foo] = this is a) echo $privateParams [' _foo '];//get This is a
So that we can easily get A
the private properties out. So what should be done with private methods? Next we look at the implementation of common methods, the implementation of public methods is relatively simple.
/**************** gets an instance of the class *******************/$class = $refClass->newinstance (); Echo $class->index ();
This makes it possible to invoke the public method. Here's a look at the private method execution
/**************** get a method *******************/$refHasClass = $refClass->getmethods ();p rint_r ($refHasClass);/*** * Array ([0] = = Reflectionmethod object ([name] = = Index [class] + A) * [1] = = Reflectionmethod object ([NA Me] = _come [class] + A)) */$come = $refClass->getmethod (' _come '); $come->setaccessible (true); Echo $come-& Gt;invoke ($class, ' This is Param ');//This is Athis was Comethis is param
getMethod()
you can get to the method by first come
, and then set come
the accessibility of the method. Finally, by invoke
executing the method
There
are many methods available for reflection, and this is not the case. Interested can look at the official documents
The above is the whole content of this article, I hope that everyone's learning has helped, more relevant content please pay attention to topic.alibabacloud.com!