What do $foo and $bar actually mean in PHP?

Let’s start with a warm welcome to anyone from around the world who is just discovering this blog. Over 1000 developers have taken part in the polls on this site and I would encourage you to participate, let your voice be heard.

Also, thanks to everyone who has bought Yii 2 For Beginners, I appreciate your support. Starting this week, I will be adding tutorials on Yii 2 that build off of examples in the book, so I hope this can be a great resource for you.

Ok, so what is up with $foo and $bar? The use of $foo, and it’s companion $bar, in examples and lessons has always bothered me. One reason for that is that I know the origin of the composite word, Foobar, which is derived from fubar. Fubar is an epression that started in the US military. It stands for “fucked up beyond all recognition.”

So once upon a time, in the early days of programming, someone apparently thought it was clever to use a phonetic variation of fubar, split in half to use in programming examples. In other words, it was a joke. It was a joke, however, that caught on, and so now we seem to be stuck with it.

So what’s wrong with that? Ok, here’s the problem. Some people, like myself, know the origin of the word. The word itself has meaning. That meaning gets injected into the example on a subliminal level, which distracts from understanding the objective of the lesson.

Also, since $foo and $bar combine to represent a single word, the first thing I always try to see is if they are meant to be related that way when they are used in an example and more often than not, they are not meant to be related, though in some cases, one is used as a child of the other. You can see how confusing this can get.

It’s not that I don’t have the brain power to overcome the inference of fubar, but on the other hand, I would rather not waste bytes or neurons, precious as they are, on something like that. I have a much better use for them elsewhere.

Now you could say I’m in the minority, and that most people, especially those around the world who don’t speak english as a first language, are not going to have that distraction and you would be right about that. However, $foo and $bar still make for bad examples. Here’s why:

Even without the inference, using $foo and $bar is like using $could_be_anything_1 and $could_be_anything_2 or as the way my brain sees it, $lazy_example_1 and $lazy_example_2.

Wouldn’t be better for example, if you were going to explain arrays to people, to do it in a way that also points them in the right direction for future use and future lessons. For example, here we have a snippet from PHP.net on the new array syntax:

// as of PHP 5.4

$array = [
"foo" => "bar",
"bar" => "foo",
];

And look, they used my favorite word for the example, I didn’t have to go far to find someone using it. So just to reiterate why this is so bad, the first key is foo and has a value of bar, the second key is bar and has a value of foo. Does this mean they are interchangeable in the code and that they are equal to each other? Of course not. Arrays don’t work that way. But imagine you were just learning. You could see how that would potentially be confusing.

Robert Martin, Author of Clean Code, uses an interesting phrase, “lies and disinformation.” He is referring to comments in code that grow outdated in time because they are not maintained as the code changes. A bad choice of language in tutorials and examples is just as harmful. It slows down the learning process and makes it less fun.

Imagine the poor guy just learning PHP and programming having to spend an extra ten minutes of his time to realize that foo and bar are not equal to each other. If that happened to me, I would be angry and want my time back. Nothing is as precious as time and anything that degrades it in a learning enviroment is as bad as “lies and disinformation.”

Imagine an array example instead:

// as of PHP 5.4 example array named basket, where “string” is key and integer is value:

$basket = [
"apple" => 1,
"cookie" => 4,
];

Now obviously, there is a little more color to the example. Also I added more to the comment for clarity, even though those aspects might be explained elsewhere. It doesn’t hurt to have it there, because when people do a Google search, they may come directly to this snippet, you never know.

Why choose the word $basket? Well, what would a future or current programmer possibly work on that would require an array? That list is probably endless, but one good example would be a shopping cart. And right away, as a human, I’m a lot more interested in the example. Arrays might be fun if I can play with apples and cookies. I might even start to get creative about what I can do with the basket.

So obviously this is as basic as it gets, but it does have implications. We have seen a movement in modern PHP towards more clear snytax, and what I mean by that is code that makes its intentions more clear.

The modern PHP frameworks like Laravel and Yii 2 have done a good job making the code more intuitive. In fact I think Taylor Otwell, Laravel inventor and developer, has been very influential in this regard. I initially found his framework very attractive, but then Yii 2 came out and as you can tell from the history of this blog, and the book I wrote about it, I fell in love with it.

An example of excellent and intuitive syntax in Yii 2 is the behaviors method that you can use on either a model or a controller. We’re about to take a quantum leap in complexity from the array example, but as long as we give a good example, we will understand it.

A typical implementation of behaviors in a model would look like this:

public function behaviors()
{
  return [
     'timestamp' => [
          'class' => 'yii\behaviors\TimestampBehavior',
          'attributes' => [
              ActiveRecord::EVENT_BEFORE_INSERT => ['created_at', 'updated_at'],
              ActiveRecord::EVENT_BEFORE_UPDATE => ['updated_at'],
                ],
          'value' => new Expression('NOW()'),
            ],
        ];
     }

Screenshot of the code with no scroll:

yii 2 behaviors

If you are following along from the book, this example appears in the User model and Profile model. We use a different type of behavior for controllers, but you can get a clear idea of how cool and how flexible this concept is.

TimestampBehavior is one of Yii 2’s out-of-the-box behaviors, so everything is in place that you need to attach it to any model. All it’s doing here is automatically setting the value of two attributes, ‘created_at’ and ‘updated_at’ with a ‘value’ of ‘NOW()’ before insert or update.

This means before any record is created or updated, the timestamp value is set, and, assuming that you have the corresponding columns on your DB table in DATETIME format, you will get the desired result and the fields in your table will be updated with the current DATETIME.

Can you see how intuitive the concept is and how clear the code is? Anyway, let’s just step through this to make sure we understand it.

By configuring the behavior, we influence how the model will work. We give the behavior a name, in this case ‘timestamp.’ We tell it what class to use, in this case ‘yii\behaviors\TimestampBehavior.’

Next we tell it which attributes we want to affect, and we use ActiveRecord::EVENT_BEFORE_INSERT to tell it when and how to use it. In other words, it will set the value of the attribute before inserting or updating, which is made fairly clear from the name of the event.

And then finally, what ‘value’ we want to give it. We’re using an instance of the expression class, which let’s us define what type of value we want, which allows us to pop in the MYSQL syntax ‘NOW()’, so ActiveRecord can hand it into the insert statement.

You know the syntax is well-written when it is easier to understand than the verbal explanation. At least it seems that way to me. I’ve been staring at it for a while now. It just seems clearer and clearer to me, which is always a good sign.

Now imagine the above example as:

 public function behaviors()
    {
        return [
            'foo' => [
                'class' => 'foobar',
                'attributes' => [
                    qux => ['baz1', 'baz2'],
                    qux => ['baz2'],
                ],
                'value' => new Expression('quux'),
            ],
        ];
     }

Screenshot of the code with no scroll:

bad behaviors

That’s not realistic, no one would do that to you, at least I hope they wouldn’t. Anyway, I think you get the point. A real example makes you want to play with the system. A $foo/$bar example is just fubar. Feel free to take the poll and let us know what you think.

Advertisements

4 thoughts on “What do $foo and $bar actually mean in PHP?”

  1. inspie of reading everything written, i could not understand and answer the questoin i have given based on $foo and $bar.Well the question is
    $foo=’bob’;
    $bar=&$foo;
    $bar=’my name is $bar’;
    echo $bar;
    echo $foo;
    could any one try to help me out!!!!!!!111

  2. Very well explained. As a PHP programmer I sometimes find $foo and $bar confusing. Your insight on this matter is really encouraging. From now on $foo and $bar are really fubar!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s