Skipping the talk of how you normally shouldn't do this, you can accomplish what you want using PHP's magic __get
and __set
functions.
class MyClass {
// add one member var that holds all the data
private $myMagicData = array();
private $another_var;
function __construct($data){
$this->example = $data; // this will auto-call the __set function
$this->another_var = $data; // this won't, since $this->another_var was declared above
}
function __get($name) {
return array_key_exists($name, $this->myMagicData) ? $this->myMagicData[$name] : null;
}
function __set($name, $value) {
$this->myMagicData[$name] = $value;
}
function exampleFunction(){
$test = $this->example; // this will auto-call the __get function
$another_test = $this->another_var; // this won't
}
}
Documentation on these and other magic functions.
Why you shouldn't do this.
In my opinion, using the magic __get
and __set
functions promotes poor programming practice. Let me demonstrate using a famous example: If a glass is half-filled, is the glass half-full or half-empty? The correct answer from a programmer's point of view is that the glass is too large. What I mean by this is, when you add the magic functions as demonstrated above, you can just keep on assigning variables and it won't care, but are they necessary?
Over time, your code will change and you might no longer need old variables that were previously assigned. Normally, you would just remove the variable declaration, meaning your class will now consume less (unneeded) memory. If you forgot to remove one of the old assignments, you'll find out soon enough. With the magic function functionality, how are you going to keep track of which variables you need, and which you don't?
Remember that code should be written primarily for humans to read, and only secondarily for machines to execute. If a second person were to join you and he wonders what variables he has access to in the view, he would either have to go through the code assigning the variables, or print_r($this->myMagicData)
, rather than just looking at the section of the class where the variables are declared.
And, of course, there is also the overhead of the magic functions getting called, which may or may not be a concern depending on the situation.
So, to summarize, manually declaring the variables you need helps:
- Keep track of what data you are and aren't using
- Makes your code easier to read for both you and others
- Performs faster
Hope this helps!