0

I'm learning PHP.

While learning PHP, I noticed that there are few entities in PHP which are used in different fashion. Sometimes with the pair of parenthesis with the enclosing parameter/s between them, sometimes with the pair of blank parenthesis(i.e. without any parameter/s or message/s passed) and sometimes without using a pair of parenthesis.

How could this be possible? Is it possible for all other entities(i.e. functions / keywords / language constructs) also that are present in PHP?

Are there any other such entities present in PHP other than 'echo', 'print', 'die', 'exit' which I come across till now?

What these entities actually are called functions / keywords / language constructs in PHP?

What's the correct method / way / coding standard to access such type of entities?

It would be better for me as well as other PHP community members who are trying to learn PHP if someone could answer all of my queries in a simple, lucid and easy to understand language with the reliable explanation?

Thank You.

PHPLover
  • 1
  • 51
  • 158
  • 311

1 Answers1

1

Normally when you see () after something in PHP, whether there are parameter(s) inside it or not, it's a function.

There are two cases where the parentheses are optional.

  1. Language constructs - the ones you've already mentioned (echo, print, die, and exit) as well as break, include, require, require_once, return, and yield. (I think that's all of the ones with optional parentheses.)
    Some language constructs, such as unset and array do require parentheses. If you're not sure whether a certain word is a function or a language construct, the best thing to do is consult the PHP manual. Language constructs will be included in this list of keywords. Some language constructs are also listed in the function reference, (for example, echo is included with string functions) but the specific manual pages will clearly indicate whether the term is a language construct, as well as whether or not parentheses are required.
    This answer has a detailed description of why/how language constructs can be used without parentheses.

  2. Object constructors with no required arguments.
    If an object constructor takes no arguments, or all of its arguments are optional, (for example function __construct($foo = null)) then the parentheses can be omitted when creating a new object. For example, for example, $now = new DateTime; and $now = new DateTime(); will both work.

As far as the "correct" way, there really isn't one. If the parentheses are required, obviously the correct way is to use them, or your code won't parse. If the parentheses aren't required, it depends on the coding standard used in the project you're working on.

Don't Panic
  • 41,125
  • 10
  • 61
  • 80