Read the definition or confused.
Can you explain what is meta-programming in PHP (Ruby) in a popular language or an example?
Reply content:
Read the definition or confused.
Can you explain what is meta-programming in PHP (Ruby) in a popular language or an example?
For example:
"Programming" is equivalent to I made a machine, this machine can help me sweep the floor (sweeping machine).
"Meta-programming" is that I made a machine that can make "sweeping machine". This machine can produce a lot of sweeping machine, it produces the sweeping opportunity to help me sweep the floor.
" meta-programming ", also called Metaprogramming , its essence is still "programming", and more than the simple "programming" is more than the ability to dynamically generate executable code.
There are a number of ways to generate code. such as the C language preprocessing macros, closures/objects and some specific structures (in Lisp macros and C + + templates) and so on ( dynamic language can be eval a direct string, although it can also be considered "dynamically generated code", but the overall should be attributed to dynamic language characteristics ).
Metaprogramming is not a useless thing to play with or a bunch of Gao Tang. Template meta-programming is the essence of C + +, and the base of C + + standard library, the well-known Ruby project is almost everywhere meta programming, and Ruby has become more expressive and implemented because of metaprogramming.
Like what:
//C++ 模板template
//对任意类型T进行声明和定义class vector{ ...};vector
vec; //编译期自动生成vector
类型的各项代码
and Ruby Meta programming
#Ruby中一个简单的类定义class D def a 'a' end def b 'b' end def c 'c' endend#=> 下面是等价代码:D2 = Class.new do [:a,:b,:c].each do | sym | #在each中动态生成三个类方法 define_method sym, { sym.to_s } end end
The simple use of meta-programming can simplify the work and, to a certain extent, make the code more expressive. The depth of meta-programming can even greatly improve the efficiency of work, but often pay the price of it needs to have in-depth understanding and practice.
In addition, PHP's dynamic characteristics are often criticized and abused, but if you can make some good packaging and design, there are some good meta-programming features.