tags:

views:

78

answers:

2

Yesterday I had a few question about OO and classes in PHP here but I have a couple new questions.

1a)
In the example snippet below you will see the 3 variables set at the top of the class and then used in a method in the class. Notice how the 3 variable declared in the beginning are not set to anything, so is it required to set/list all variables a class will use at the top like that?

1b)OR are they just called at the top to set them to be protected/private/public?

1c) Is it always required to set a variable like that, let's say all the vars are public, would you still need to set them at the beginning?

<?PHP
class widget{
    private $name;
    public $price;
    private $id;

    public function __construct($name, $price){
     $this->name = $name;
     $this->price = floatval($price);
     $this->id = uniqid();
    }
}
?>
+2  A: 

Variables declared within a class declaration but not within a method are "member variables" of that class - they're scoped to the class only but are available to all methods of that object, and a new set of each will be created for each instance of the object.

$a = new widget("first", 0.1);
$b = new widget("second", 0.2);

echo $a->price; // will echo 0.1
echo $b->price; // will echo 0.2
echo $price; // will not echo anything unless you set $name to something elsewhere

echo $name; // will not echo anything unless you set $name to something elsewhere
echo $a->name; // will give you an error since 'name' is private to the class
Amber
+1  A: 

If you want to set the scope of the variable, you need to declare it in the class declaration like you did above. If you just want the variable to have a public scope, you can set it on-the-fly within a method by simply using:

$this->variable_name = "value";

A variable declared in that fashion will be available in any method within the class, and also in any of the methods in any sub-classes (classes that extend this class).

BraedenP