Dynamic Features of PHP language-Aspect-Oriented

Source: Internet
Author: User
More examples of Dynamic Features in PHP

The following example is similar to object-oriented programming. What is different from object-oriented programming is that object-oriented programming focuses on the integrity of each object definition,

The aspect is concerned with some specific functional aspects of the entire object system, such as logs and filtering. These specific functional aspects are stripped out for sharing purposes.

Listing 8. Simple user class

<?phpclass User{  private $name;  function set_name( $value )  {    $this->name = $value;  }  function get_name()  {    return $this->name;  }}$c1 = new User();$c1->set_name( "Jack" );$name = $c1->get_name();echo( "name = $name\n" );?>

This object is simple enough. What should I do if I want to record logs when setting or reading the username?

You can create a dynamic log processing object and wrap the user object in it. It seems that the action of the user object will be the same as that of the packaged log class.

Listing 9. Dynamic packaging class

<?phpclass Logged{  private $obj;  function __call( $method, $args )  {    echo( "$method( ".join( ",", $args )." )\n" );    return call_user_func_array(array(&$this->obj,$method), $args );  }  function __construct( $obj )  {    $this->obj = $obj;  }}$c1 = new Logged( new User() );$c1->set_name( "Jack" );$name = $c1->get_name();echo( "name = $name\n" );?>

The call code is the same, but this time, any access to the user method will be echo. (You can replace echo with other logic, such as security control, logging, and data filtering)

It is like a user object is mounted by a hook function when the method of the user object is called, and is pre-processed or post-processed.

By iefreer

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.