PHP Variables – Why Creating Variables on the Fly is Discouraged

PHPvariables

Are you guys familiar with those pesky PHP notice errors? You know, the ones that will appear when you do something like this:

if($some_variable == 45)

But if $some_variable wasn't created already, PHP will be like "Hey! Idiot! This variable wasn't defined yet!" and output a Notice Error onto the screen. However, you can simply turn PHP Notice Errors off by using error_reporting(0) and the application works perfectly. What's the point? Who cares if a variable wasn't created yet? Why can't you just create it on the fly inside the if statement? I feel like this is the easy, no-brainer way to do it, but apparently PHP discourages this practice. Why?

What I find myself having to do a lot of times is something like this:

if(isset($some_variable) && $some_variable == 45)

If $some_variable is not set, the if statement automatically fails, so the second condition of the if statement is never checked, so the Notice Error never happens. This works great, but I feel like it shouldn't be necessary. Some of the applications I am working on are huge and I fear that the extra added conditions will slow down my poor old server if there are dozens of instances of it, combined with thousands of users. I know that this is just a single extra statement which would be O(1), which isn't a lot of resources, but it's still something I worry about. Should I not worry about O(1) even if I hypothetically were to have thousands of users? Am I caring too much about being efficient?

I know PHP Notice errors can easily be turned off by using error_reporting(0). I'm not sure if certain types of errors can be turned on/off as desired because I haven't researched error_reporting() extensively.

My question is what's the point? Why is it discouraged to create variables on the fly? I feel like creating variables on the fly may be a little bit lazier but is 10000000x easier to program and should be the no-brainer encouraged way to do it.

This is meant to be both a philosophical and a technical question.

Best Answer

While sometimes I think it would be nice to be able to create variables on the fly without generating those pesky "notices", I can often see the advantages of not being able to do so.

I think the biggest benefit to explicitly declaring variables, or checking that variables are set, is code readability. The isset in your example indicates to the person reading the code that $some_variable may not be set. While this doesn't necessarily save much time (as they'll see that it isn't set when they read the notice), it provides the reader with more information, which is always beneficial.