Forum Moderators: coopster
class definitions include a list of properties - or variables. In many code examples, I have seen classes in which there are variables used throughout the code that weren't declared at the top. What's the deal here? Is it required?
here's an example of this
class A {
public $var1;
public $var2;
function __construct(){
$this->var1 = '';
$this->var2 = '';
}
public function func1($pass){
$var3 = $pass * 2;
echo $var3;
}
}
was $var3 supposed to be declared at the top?
what if it was changed to:
$this->var3 = $pass * 2;
echo $this->var3;
would that make a difference? is that wrong?
also, the problem I'm encountering relates to a pagination class (Pagination.class.php) that I'm trying to attach to everything that requires pagination. I made the pagination class and made two other classes: class A and class B
i wrote the top of these like so:
<?php
include 'Pagination.class.php';
class A extends Pagination {}
?>
and
<?php
include 'Pagination.class.php';
class B extends Pagination {}
?>
Is there something fundamentally wrong with this? I have been searching like crazy for answers and have found a ton of resources, but no answers to these questions.
public function func1($pass){
$var3 = $pass * 2;
echo $var3;
}
}
I have had issues getting constructors to load from parent classes, so if you code is based on the constructor from a parent class then I would check that this is actually getting loaded into the child class.
If you're including both your class A and class B scripts in another script, try replacing
include 'Pagination.class.php';
in each of them with
include_once [php.net] 'Pagination.class.php';
$var3 is just a local variable in the function in your example. $var1 and $var2 are, as you mentioned, properties or member variables of the class. $var3 doesn't exist outside func1() whereas $var1 and $var2 exist as long as a class object exists. They aren't global per se, they are local to a particular object:
$obj1 = new A;
$obj1 -> var1 = 7;
$obj1 -> var2 = 8;
$obj2 = new A;
$obj2 -> var1 = 3;
$obj2 -> var2 = 4;
$obj1 and $obj2 have different values for their member variables.