PHP

Is there a problem with not declaring a variable in PHP?

April 14, 2022

Is there a problem with not declaring a variable in PHP?

In this article, we will see if there is a problem with not declaring a variable in PHP – and what this may imply in the quality of our software.

not declaring a variable in PHP thumb

Hey you programmer, ok? Let’s learn more about variable declaration and PHP!

In the PHP language we do not have explicit declarations of variables and this may confuse many who start their studies in it

In other languages we have reserved words like: var, let and const

What happens then is that in PHP variables are always initialized when they are used for the first time.

So What Should We Do?

As a good practice, variables in software are initialized at the top of the software.

So we can keep this pattern in PHP too, declaring them at the beginning of the code

And if necessary, create comments explaining their role in the system

That is, before any logic in the code, declare the variables you will use with clear names for their purposes.

You can use camelCase too:

// bad
$x = 0; 

// good
$orderNumber = 0; 

// bad
$cartitems = 0; 

// good
$cartItems = 0;

Above some examples comparing bad and good ways to declare variables, with objective names and camel case

Avoid generic names like: x, y, value, total

And also use as few variables as possible to improve code maintainability.

Also making it easier to read

Conclusion

In this article we learned the problem of not declaring a variable in PHP

We won’t get any errors from PHP as there is no explicit declaration of variables

So we should always opt for the good practice, which is to declare variables at the beginning of the code, with objective and non-generic names

Also taking care to use as few of them as possible, so there is no confusion when reading the code.

Do you want to learn more about PHP? Click here!

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x