Usually when I write a PHP class I have done something like this:
class MyClass () {
public attribute1;
public attribute2;
public attribute3;
}
Is it possible to set attributes based on logic?
class MyClass () {
public function __construct() {
if (some condition) {
public attribute1;
attribute1 = 23;
} else {
public attribute1;
attribute1 = 55;
public attribute2;
attribute2 = 11;
}
}
}
Like others said, use
$this->param = 11;, but I don’t like this idea, because I don’t like undeclared variables in my classes.Declaring variables in a class definition is for readability, and you can set private, public and protected. In java this is not permitted, and so should be in php, it should be error.
If your don not know what variables you will use, use magic methods _get() and _set().
Example code:
Output: