Reputation: 307
My question is very simple, I saw this code in a class:
class controller_activity {
function __construct($args) {
//the variable template is not defined or what happen??
$this->template = new Template('activity');
}
.......
Usually I see the declaration of variables in a class like "public $template" or similar, but this case, is the same that if I define those variables as usual?, can I add variables in this way directly?, without defining them before?, is it recomendable?
Upvotes: 1
Views: 354
Reputation: 11
The code you posted will work without a problem.
In PHP you can use undeclared variables. In other languages (like Java), you can't use undeclared variables. It's simply a matter of style, but I personally don't like using them.
Note that the template var, if undeclared as in your example, has public visibility
Upvotes: 1
Reputation: 6346
While not recommended, PHP and it's non-constraining (weakly typed) use of variables means that it is possible to declare class vars on the fly.
I've done it by accident on a number of occasions, but then gone back and defined them properly. By default they will have the public
access method (the same behavior as not including an access method at the head of the class, i.e. $var = 0
versus private $var = 0
).
Again, this is not recommended. I haven't tested for it specifically, but I would imagine that they throw a Notice
error. The other issue is that doing this makes code harder to follow, either for yourself later on or another developer trying to work with your class.
Upvotes: 1
Reputation: 26056
I think the reason why this code works is because the $this->template
assignment is happening in the __construct()
which happens pretty much immediately on class instantiation. So this could be seen as a sloppy—but fudgable—way of doing variable assignment. But it doesn’t help for readability or debugging later on. So the answer is yes, you can do this. Is it a "best practice?" 100% no.
Upvotes: 1
Reputation: 197624
is the same that if I define those variables as usual?,
No, the definition is missing. get_object_vars
will show them, but get_class_vars
won't.
can I add variables in this way directly?,
Yes, that is possible. They will be publicly visible.
without defining them before?,
Yes, without defining them before. They will be publicly visible.
is it recomendable?
That depends. Normally not, but there are exceptions to this rule.
Upvotes: 1