Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 484
Zacky112 Avatar asked Jul 15 '10 09:07

Zacky112


People also ask

What the language constructs actually do?

In computer programming, a language construct is a syntactically allowable part of a program that may be formed from one or more lexical tokens in accordance with the rules of the programming language. The term "language construct" is often used as a synonym for control structure.

What is language construct in Java?

Language constructs are part of a program that is formed from a combination of one or more tokens which syntactically acceptable and are as per specified rules of programming language.

What keyword is used at the start of every PHP variables before its actual name?

Rules for PHP variables: A variable starts with the $ sign, followed by the name of the variable. A variable name must start with a letter or the underscore character.


3 Answers

Language constructs are hard coded into the PHP language. They do not play by normal rules.

For example, whenever you try to access a variable that doesn't exist, you'd get an error. To test whether a variable exists before you access it, you need to consult isset or empty:

if (isset($foo))

If isset was a normal function, you'd get a warning there as well, since you're accessing $foo to pass it into the function isset. Since isset is a language construct though, this works without throwing a warning. That's why the documentation makes a clear distinction between normal functions and language constructs.

like image 171
deceze Avatar answered Oct 25 '22 00:10

deceze


Language constructs are what makes up the language: things like "if" "for" "while" "function" and so on.

The mentions in the PHP manual of things like "echo", "die" or "return" are there to make it clear that these are NOT functions and that they do not always behave like functions.

You could call "echo" as "echo()" so it may confuse beginners. That's why they put the clear disinction in the manual. To make it absolutely clear to everyone.

Other examples for language constructs that could be mistaken for functions are "array()", "list()" and "each()".

like image 20
selfawaresoup Avatar answered Oct 25 '22 00:10

selfawaresoup


To understand the answer for this question you must understand how parsers work. A language is defined by syntax and the syntax is defined through keywords.

The language constructs are pieces of code that make the base of PHP language. The parser deals with them directly instead of functions.

like image 44
Narcis Radu Avatar answered Oct 25 '22 01:10

Narcis Radu