OOP question

Im a bit confused about setting Class attributes. If you have a private attribute at the start of a class you can set it when running a Class method e.g.

class Test {
private $attribute

public function test_function() {
$variable = 3;
$variable = $this->attribute;
}
}

Later you can use the private $attribute in another method by using $this->attribute.

However i have just tested some code i am working on and deleted the private $attribute at the start of the class but i could still use it in a new method by using $this->attribute. Does this mean that i dont need to store values in attributes if i want to use them somewhere else within a class? And if so, what are attributes actually used for?

Thanks

Yes, you can call an attribute that is not explicitly declared and PHP will just use it as if it was declared.

The advantage of explicitly declaring them is that:

  1. You (and your colleagues!!) know they exist by looking at the start of the class
  2. You can set a visibility, i.e., public, protected or private; implicitly created variables are public IIRC.

So, even though you can use variables without declaring them, I wouldn’t recommend it.

Thanks Scallio, that clears it up.