Persons new to programming often have difficulty grasping the concept of language constructs. Furthermore, both new programmers and seasoned programmers often get tripped up when it comes to telling the difference between language constructs and functions as they often resemble each other and in many instances are used in the same way. As a result, many developers write code for a number of years mistaking language constructs for functions and only become aware of the difference after trying to fix some odd quirk in their applications which arises because of a misunderstanding of the fundamental differences between the two.
Essentially, a function is a block of code which is written in such a way that it may be used and reused multiple times in the execution of a script. It may be designed to accept arguments and return values or it may do neither. If it is designed to take arguments, they will invariably affect the procedures of the function and, quite likely, any value(s) returned by the function. In PHP, functions may be compiled with the language (referred to as core or native functions), they may be user defined (i.e. created by the programmer writing the script) or they may be accessed as components of external libraries or extensions available via PECL. Examples of PHP functions include:
Language constructs are keywords that are a part of the syntax of the language, i.e. they are parts of the language itself. They cannot be user defined nor can they added to the language via extensions or libraries. They may or may not take arguments and they may or may not have return values (although most of them don’t). Examples of language constructs in PHP include:
Note that some language constructs do not require the use of parentheses:
print('one'); //works in the same way as print 'one'; //the above code outputs 'oneone' and include('file.php'); //works in the same way as include 'file.php';
The key difference between functions and language constructs is that language constructs are the most basic units of the language and cannot be broken down further by the PHP parser whereas functions have to be further broken down before being parsed, often into language constructs. In other words, in just the same way that PHP code has to be broken down into lower level opcode by the PHP parser in order for the machine to understand it, functions must be broken down to language constructs by the PHP parser before they are parsed. There are a few interesting consequences of this:
- Language constructs tend to be faster than their function counterparts.
- Language constructs in some cases may be able to bypass error handling mechanisms.
- While functions can be disabled in PHP via the configuration file, language constructs cannot.
- Language constructs cannot be used as callback functions.