Reputation: 1035
I've never really bothered to predefine variables or for that matter, defined what type of variable it is. I'm trying to improve my code by doing these things.
I've read that it's better practice to predefine PHP variables but can't find much information on the benefits when it comes to defining a type.
I'm interested to know if there are any speed benefits and hear what other people have to say on the subject.
Upvotes: 1
Views: 229
Reputation: 12018
For code readability it is advisable to define your variables outside of the scope that uses them. PHP allows you to create variables inside a block such as an if statement or loop and then use that variable outside that block scope. This is very confusing when you try to edit someone else's code.
So for the sake of easy refactoring and code readability you should define your variables outside of block statements that use them.
As for defining types, PHP is not a strongly typed language. About the best you can do is use typing hinting and define object types in your function declarations.
Upvotes: 0
Reputation: 174967
The benefit is purely in readability.
In theory, you could do
$var = 42;
$var = "Hello World!";
$var = false;
And it would be fine. However, that doesn't make sense in most applications, nor is it very readable (spread those lines around a 1000 line page, and you'll understand what I'm saying).
Predefining a variable gives you a clear understanding of what the variable holds, and what its purpose is.
It should be used in conjunction with
Upvotes: 3