Jump to content

Variable declaration


LittleJoe

Recommended Posts

In application programming it's often best practise if not necessary to declare variables at the start of functions instead of just anywhere inside the function when first used. Does this make any difference in PHP?

function MyFunction(){$myVariable; // A lot of code $myVariable = OtherFunction();}

VERSUS

function MyFunction(){// A lot of code $myVariable = OtherFunction();}

Link to comment
Share on other sites

I declare them up-front though I don't think it makes a difference if they're not declared at the beginning.

Link to comment
Share on other sites

In PHP, variables are declared the first time you use them. I don't find it convenient to have an extra line of $var1; $var2; $var3; at the beginning of a function.

Link to comment
Share on other sites

especially if the variables are meant to be used in conditional structure it is best to explicitly initalize variable as default value before you use them.

Link to comment
Share on other sites

In strongly typed languages, you declare variables at the top of functions so that the compiler can allocate memory. PHP is weakly typed and allocates memory dynamically, so this type of declaration is not required. As others have pointed out, there may be practical reasons for naming/defining a variable before it is used, but this is not the same as a requirement.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...