Forum Moderators: coopster
what is the point of declaring vars - and which vars should be declared?
Declaration allows compiler to warn you when you have accidentally created new variable with same name as the other in the same scope, and further operations will be done with local var rather than global one.
This sort of errors are hard to spot because logic looks just right, but you can't see other declarations that were made outside of the function where as the compiler has global world view of your code.
For example:
class test {
function var($var) {
$this->var = $var;
return $this->var;
}
}
Is just as legal as:
class test {
var $var = '';
function var($var) {
$this->var = $var;
return $this->var;
}
}
However I myself like to pre-define the vars ahead of time just so I know what all is there.
class class1
{
var $var1=7;function func1()
{
$this->var1 = (isset($this->var1))? $this->var1 + 1 : 1;
return $this->var1;
}
}
class class2
{
function func2()
{
$this->var2 = (isset($this->var2))? $this->var2 + 1 : 1;
return $this->var2;
}
}
$class1 = new class1();
$class2 = new class2();
echo $class1->func1(); // returns "8"
echo $class1->var1; // returns "8"
echo $class2->func2(); // returns "1"
echo $class2->var2; // returns warning - undefined
In other words, class2 could be rewritten as
class class2
{
function func2()
{
$var2 = (isset($var2))? $var2 + 1 : 1;
return $var2;
}
}
It probably means that you simply aren't using the object properties outside their scope. In other words, you aren't using a function to set
$this->prop = 6;
in a class function and then trying to access it outside the function as
$var = $obj->prop;
If the variable is only being used locally within the class, then that's normal,
Actually, it's a bit more specific than that. What I said above applies within a class as well. If you do not have a var declaration and you use that var in two different class functions, that info won't be shared.
Let's assume that you have error reporting turned down so it doesn't stop at the undefined variable.
class classy
{
function func1 {
$this->myvar += 7;
echo $myvar;
}
function func2 {
$this->myvar += 7;
echo $myvar
}
}
$obj = new classy();
$obj->func1(); // outputs "7" regardless of var declaration
$obj->func2(); // outputs "7" if no var declaration; "14" if there is one
So in your classy example, declaring $myvar outside of the class (preceding it's functions invocation) will turn $myvar into a "global" variable, and not declaring it (like the example) renders it a "local" (to each function separately within the class) variable?
And in either case, having register_globals turned on will have no effect on that example?