7

I know the concepts of Pass-by-value, Pass-by-reference, etc... So, I understand why explicitly defined functions throw a warning when the parameter is not defined.

But, if empty() and isset() are functions, then why doesn't it throw a warning when an undefined variable is passed? Is there some exceptional magic going on here? How do I replicate it?

BlackPanther
  • 1,732
  • 1
  • 14
  • 19
  • possibly closely related: [What are language constructs and why do we need them?](https://stackoverflow.com/q/3254327/476) – deceze Oct 02 '17 at 08:22

1 Answers1

6

empty() and isset() are not actually functions.

They're keywords built into the language, and executed by the compiler, which is how the behavior in question is possible - the compiler (unlike the runtime engine, where regular functions execute) already knows if a variable exists or not.

As a side effect, that's why in PHP 5 you couldn't define class methods named empty(), isset(), list(), etc. And you still can't declare classes, or constants via const using the same names.

Some other languages provide this as a feature called fexpr.

Narf
  • 14,600
  • 3
  • 37
  • 66
  • Ok. I get it. Is there a way to replicate this in a function I make, without adding to the language itself? – BlackPanther Oct 02 '17 at 08:06
  • Thanks @Narf. I was really confused about how the control & data flow worked in their cases. Now, I think I get the idea. Just one more question. They can process $_POST, $_GET and $_REQUEST too. Aren't they bound at runtime? or are they done by the time compilation of the page is over? – BlackPanther Oct 02 '17 at 08:17
  • 1
    Yeah, talking about the "compiler" here is somewhere between confusing and incorrect I'd say. Simply regard these language constructs as something like operators. `->` (as in `$foo->bar`) also works "at runtime" and does something you can't replicate using PHP code; or, say, `instanceof`… same for `isset` and `empty`. – deceze Oct 02 '17 at 08:19
  • 1
    @BlackPanther Super-globals are a bit special, yes - they're available before any of your code executes. But that doesn't really matter for `empty()` and `isset()`. – Narf Oct 02 '17 at 08:24
  • @deceze I understand that now. But, empty() and isset() made more sense as functions than language constructs to me. Unlike instanceof, include, etc. they are called similar to functions, the parameter is 'passed', and they return a boolean value. That 'passing parameter' part was the only giveaway... – BlackPanther Oct 02 '17 at 08:27
  • 2
    @Black Virtually all operators also return values, that's not a criterion. The syntax looks an awful lot like a function call, but that's really irrelevant. There's nothing that dictates what an operator must look like syntactically. – deceze Oct 02 '17 at 08:30