首页 > 代码库 > Naming variables

Naming variables

Variables are a fundamental building block of all programming languages. In this lesson, I‘ll describe briefly what a variable is, explain the basic rules for naming variables(注意区分和JS的不同命名规则), and offer some advice on choosing variable names. Put simply, a variable is a placeholder for a value that you either don‘t know or that might change. If that brings back bad memories of Algebra(哈哈,我代数还可以,几何不太好~~) at school, don‘t worry. We use variables in everyday life without thinking twice about them. Hi, my name is David.

What‘s your name? In this case, name is a variable. When talking about me, name has the value David. But in your case, in might be Dan, Denise, or Peach‘s honey blossom. When you go to the checkout in an online store, it tells you the total of what you have to pay for the goods and delivery, it‘s a different value each time, but it‘s always called Total. So, that‘s essentially what a variable is. The name of the variale always remains the same but it can represent different values depending on the circumstances. When creating variables in PHP, you need to follow some basic rules. The variable name must always begin with a dollar sign. The first character after the dollar sign cannot be a number. You can‘t use any spaces or punctuation marks, except the underscore. So, in essence, you‘re limited to letters, numbers, and the underscore. And variable names are case-sensitive.

As long as you follow those basic rules, you can name your variables just about anything you like, with a couple of exceptions. This is reserved for use in PHP object-oriented scripts, and you should avoid using any of the reserved words listed at this URL on the PHP website. It‘s best to choose names that tell you what the variable is for. Some people use really short names of just one or two letters to try to reduce the amount of typing they have to do. But except in a handful of cases, which we‘ll explain later in this workshop, it‘s a really bad idea.

You might understand what the variable is for now, but if you need to update your script in six months time, you probably won‘t have a clue. Good variable names make your code easy to understand and maintain. Often, it‘s a good idea to use multiple words in a variable name. Use camel case or the underscore to distinguish between the words. Camel case capitalizes the first letter of each subsequent word, as shown here. The end of name is in uppercase. But don‘t forget that variables are case-sensitive.

If you spell first name all in lower case, PHP will treat it as a different variable. Here, I‘ve used an underscore to distinguish between the two words. Both naming conventions are equally acceptable. So, to recap, always begin variable names with a dollar sign, use only letters, numbers, and the underscore. And remember, the first character after the dollar sign cannot be a number.

Naming variables