PHP Reflection mechanism Usage Instance Code

Source: Internet
Author: User
This article mainly introduces the use of PHP reflection mechanism, is a more important concept in PHP programming, the need for friends can refer to the following

In this paper, the use of the reflection mechanism of PHP is described and shared for everyone's reference. Here's how:

The demo sample code looks like this:

<?phpclass Classone {  function Callclassone () {    print "in Class one";  }} Class Classonedelegator {  private $targets;  function construct () {    $this->target[] = new Classone ();  }  function call ($name, $args) {    foreach ($this->target as $obj) {      $r = new Reflectionclass ($obj);      if ($method = $r->getmethod ($name)) {        if ($method->ispublic () &&! $method->isabstract ()) {          return $method->invoke ($obj, $args);}}}}  $obj = new Classonedelegator (); $obj->callclassone ();? >

Output Result:

In Class One

It can be seen that the proxy class Classonedelegator instead of the Classone class to implement his method.

Similarly, the following code is also capable of running:

<?phpclass classone {function callclassone () {print "in class One";  }}class Classonedelegator {private $targets;  function AddObject ($obj) {$this->target[] = $obj;      The function call ($name, $args) {foreach ($this->target as $obj) {$r = new Reflectionclass ($obj);          if ($method = $r->getmethod ($name)) {if ($method->ispublic () &&! $method->isabstract ()) {        return $method->invoke ($obj, $args); }}}}} $obj = new Classonedelegator (); $obj->addobject (New Classone ()); $obj->callclassone (); 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.