Use class properties or pass data around as method arguments
Posted: Sun Mar 08, 2015 5:47 pm
I know basics of OOP and I use it for every project including more than about 100 lines of code. However I have a nagging question.
If I have a class that accepts some data through its public method(s) and then does something with/to that data with protected/private methods, is it better to use class properties, or pass data around as method arguments? For example:
Would it be better instead to pass the data to the check() method as arguments without creating class properties, like this:
As far as I can say, not creating additional variables would decrease memory usage slightly (or am I wrong), but on larger projects this kind of code would get too cumbersome, at least for me. On the other hand, for some simpler things, the latter approach seems more elegant because there's less code involved.
So, what can you tell me about advantages and disadvantages of these two approaches.
Thanks in advance.
If I have a class that accepts some data through its public method(s) and then does something with/to that data with protected/private methods, is it better to use class properties, or pass data around as method arguments? For example:
Code: Select all
class Example{
private $_foo;
private $_bar;
public function insert($foo,$bar){
$this->_foo = $foo;
$this->_bar = $bar;
if($this->check()){
//insert into DB or do some other things
}
}
protected function check(){
//some validation code, return true or false
}
}Code: Select all
class Example{
public function insert($foo,$bar){
if($this->check($foo,$bar)){
//insert into DB or do some other things
}
}
private function check($foo,$bar){}
}So, what can you tell me about advantages and disadvantages of these two approaches.
Thanks in advance.