back

Bendegúz Csirmaz

This post is part of a series based on a presentation I gave at Cheppers on March 20, 2019.

PHP quiz #2 - echo arguments

Echo was the first PHP statement I learned. It went great: I printed 'Hello, World!' to the screen and quickly moved on to more challenging problems. If only everything in programming was this easy.

Question

What will this code output?

<?php

function a() {
  echo 'a';
  return 'a';
}

echo 'b', a(), "c\n";
  • A
    bac
    a
  • B
    baac
  • C
    abac
  • D
    abc
    a

Answer

Show the answer
B
baac

Explanation

Evaluation strategy

Arguments are usually evaluated before they're passed to a function. This is called eager evaluation.

Echo works a little differently. The arguments are not evaluated eagerly (in which case the answer would be "abac"). They are evaluated one by one.

Calm down!! There is a reason for this. It's quite logical, actually.

Variable declarations

Many programming languages allow multiple variable declarations in one line. It's considered a bad practice in all of them.

In PHP, variable declarations can be shortened the following way:

<?php

class A {
  public $a = 'a', $b;
}

function b() {
  global $c, $d;
  static $e = 'e', $f;
}
<?php

class A {
  public $a = 'a';
  public $b;
}

function b() {
  global $c;
  global $d;
  static $e = 'e';
  static $f;
}

As you can see, using commas is essentially the same as writing consecutive statements. It is legal in PHP, albeit discouraged because of readability reasons.

Language constructs

Echo is not a function. It's a language construct, like 'public', 'global' and 'static'. It has special meaning for the interpreter.

Although it doesn't have much in common with variable declarations, it handles multiple arguments in a very similar way:

echo 'b', a(), "c\n";
echo 'b';
echo a();
echo "c\n";

Passing multiple arguments to echo is the same as writing separate, consecutive echo statements.

Conclusion

In modern PHP applications echo statements are buried in the depths of template systems.

They might be rarely needed in one's day-to-day work, but they're still one of the most fundamental PHP statements. It's worth knowing how they work.

Alright! We've learned enough about language constructs for now. In the next post we'll take a look at operator associativity.

<< previous

next >>