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

Viewed 7547

I keep coming across statements like:

echo is a language construct but print is a function and hence has a return value

and

die is a language construct

My question is what are these language constructs and more importantly why do we need them?

7 Answers

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(…); isn’t.
Related