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