PHP: What are language constructs and why do we need them?

后端 未结 7 841
时光取名叫无心
时光取名叫无心 2020-12-17 15:12

I keep coming across statements like:

  • \"echo is a language construct but print is a function and hence has a return value\"
  • \"die is a language constr
相关标签:
7条回答
  • 2020-12-17 16:01

    For the sake of completeness, a language construct is any instruction which is built into the language itself, while a function is an additional block of code.

    In some cases, a language may choose to build in a particular feature or to rely on a separate function.

    For example, PHP has the print language construct, which outputs a string. Many other languages, such as C don’t build it in, but implement it as a function. There might be technical reasons for taking one or other approach, but sometimes it is more philosophical — whether the feature should be regarded as core or additional.

    For practical purposes, while functions follow a rigid set of logistic rules, language constructs don’t. Sometimes, that’s because they may be doing something which would otherwise traumatise a regular function. For example, isset(…), by its very purpose, may be referencing something which doesn’t exist. Functions don’t handle that at all well.

    Here are some of the characteristics of language constructs:

    • Many don’t require parentheses; some do sometimes.
    • Language Constructs are processed in a different stage; functions are processed later
    • Some Language Constructs, such as isset do things which would be impossible as functions; some others, such as Array(…) could have gone either way.
    • Some Language Constructs certainly don’t look like functions. For example, the Array(…) construct can be written as […].
    • As the documentation keeps reminding us, language constructs cannot be referenced as variable variables. So $a='print_r'; $a(…); is OK, but $a='print'; $a(…);
    0 讨论(0)
提交回复
热议问题