Friday, September 4, 2015

Language Constructs in PHP

PHP has a huge collection of built-in functions that you can call directly within your PHP files. While going through built-in functions, you might have faced the term language construct.

For an example you might have seen that echo() is not a function but a language construct. In addition to echo() following are some other language constructs.

1.print()
2.unset()
3.isset()
4.empty()
5.include()
6.require()
7.die()

Any computer language is made up of basic elements and these elements are known by their respective language parsers. For an example if is a basic element in PHP and PHP parser is aware of it.

So when a PHP file is going through PHP parser, if it sees an if then it knows that there should be a left parenthesis next to that. If not, PHP parser would throw an error. Here we can call if is a language construct because PHP parser knows what it is without further analyzing.

In a similar way we can think that PHP parser recognize and know what to do when it sees echo() or any other language construct. When PHP parser finds a built-in function, first it needs to check the language definitions and convert the function into set of known language constructs.
Language Constructs Are Relatively Faster

If you research on language constructs vs built-in functions, you might have seen that it says language constructs are relatively faster over built-in functions since they are basic elements of the language.

However you shouldn’t think about the difference in anything more than microseconds. And also final execution time depends on the parameters that are passed into language constructs or built-in functions.
Language Constructs Don’t Need Parenthesis

1.echo ('Today is a beautiful day');
2.echo 'Today is a beautiful day';
3.$today = 'Today is a beautiful day';
4.echo $today;
5.
6.die('You are not authorized to access this content');
7.die;

All above coding lines are correct and processed as expected. Note that echo() and die() both are language constructs and they can be used with or without parenthesis. However you can’t use built-in functions without parenthesis.
1.
count($namesArray); // This is correct assuming that $namesArray is defined.
2.
count $namesArray; // This is incorrect. It's identified as a syntax error.

No comments:

Post a Comment

How to Host a Laravel Project on Hostinger’s hPanel: A Step-by-Step Guide

How to Host a Laravel Project on Hostinger’s hPanel: A Step-by-Step Guide If you're looking to host a Laravel project on Hostinger’s hPa...