Tag Archives: php coding style

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.

Yii 2 PSR Coding Standards

I’d like to take a moment and welcome everyone who is finding their way to this blog. We have readers from all over the world. A lot of people have voted in the polls and the most active one is on my Yii 2 vs. Laravel post. Over 700 people have voted in that poll, so thank you to everyone who has participated.

Recently I read the book Clean Code by Robert Martin and it got me thinking about coding style and standards. I saw on the news release for Yii 2 that it follows the PSR standards, however I found some instances in using Yii 2, where it’s not following the standard.

For example, the naming of a private variable in the LoginForm model:

class LoginForm extends Model

public $username;
public $password;
public $rememberMe = true;

private $_user = false;

Accodring to the PSR-2 standard:

Property names SHOULD NOT be prefixed with a single underscore to indicate protected or private visibility.

Personally, I like the way Yii 2 is doing it there, it seems very intuitive to me and I couldn’t understand why the PSR standard would be against it. So I posted a question about in the Yii 2 forum and got an excellent response from forum member DocSolver. This is what he said:

“An argument in favour of the PSR-2 standard: if you change the status of a property from protected to public, you have to refactor all references to it.

The underscore in the name reminds me of to the old programmer’s habit of prefixing a variable’s type in its name (e.g. “floatAmount” and “strCustomerName”), which was popular in older languages when IDE’s were nonexistent. But now these habits are considered a bad practice by authorities such as Robert C Martin (see book “Clean Code”).

Because of this, I would say that your IDE should notify you about a variable being protected, instead of a naming convention that will probably be violated by many people. So I would vote in favour of conforming the Yii2 codebase to the PSR-2 way.”

DocSolver made some excellent points. But one thing to keep in mind is that the Clean Code book covers Java, which is a strongly typed language anyway, meaning that the variable type is explicitly stated with descriptors like string and int. So java gives you more hints going in.

Personally, I like the underscore because it pops out at you like a speed-bump. For example, in the code snippet above, it helps me understand that $_user is not from the form input, it really jumps out at you as different.

Anyway, this might be microscopic overkill on style, but I do feel standards are important and should be respected. One of the main points in the Martin book is that programmers spend much more time reading code than they actually spend coding. It’s so true. And that means things like this become important because it’s likely someone will have to read your code and the easier it is for them to understand it, the better.

I wrestled with this issue a bit because I would be much more comfortable using the underscore for private variables, just seems to have stuck in my head as a good way to go, but I’m going to sacrifice that peace of mind I get doing it that way to stick to the standard. I think following the standard is actually more important, at least in this case. Plus DocSolver made a pretty convincing case of why following the standard is actually better.

Internally, we can resist change, but that is just a form of inertia. I remember friends being resistant to the new array notation because they were so used to the old style, which to me looks like dinosaur code. I don’t want to be in the dinosaur camp.

I’m not a fan of mindlessly following what we think others expect from us. I think the controversy on TDD is an example of that. On the other hand, when programmers come together to set a standard, it’s worth taking it seriously.

In terms of Yii 2 projects, I will not be refactoring the framework code just for the sake of eliminating an underscore, that would silly. Plus, I would probably just mess it up anyway. I’ll just be mindful for my future code, when creating a private property, to keep it clean of the identifying mark. Let us know what you think. Take the poll and let us know if you follow the PSR-2 Standard.