Reputation: 1176
I'm wondering when private/protected methods should work on the class it's variables (like $this->_results
) and when such methods should be used as if they were functions (like $this->_method($results)
). Examples below:
<?php
class TestA
{
protected $_results;
public function getResults()
{
$this->_results = getFromWebservice();
$this->_filterResults();
}
protected function _filterResults()
{
$this->_results = doMagic($this->_results);
}
}
<?php
class TestB
{
protected $_results;
public function getResults()
{
$results = getFromWebservice();
$this->_results = $this->_filterResults($results);
}
protected function _filterResults($results)
{
return doMagic($results);
}
}
Upvotes: 0
Views: 170
Reputation: 14329
Using exclusively the example you've given there is no difference whatsoever between the two methodologies. You could extrapolate to find differences, but they are not actually present.
My guess is that you are trying to implement a class without designing it first. Because the picture is not complete, there are no obvious reasons to choose one methodology over the other.
When you start to flesh out exactly what you want to do, you will likely discover that method one binds the filtering routine to the class, whereas method two encourages the routine to be separated from the class.
Method one
Method two
filterResults
is no longer a logical name but rather something like applyXyzFilter
, which is hard to justify keeping in the classUpvotes: 1
Reputation: 101956
As long as you are sure, that you need to maintain only one results variable per instance always use the first version (which works on the class property). That's one of the purposes of using classes: to have shared variables.
You may actually consider the class properties as arguments to your methods, which are implicitly specified. (If you're programming in C++ you know that at least there it really is that way. For example you can specify that you are not going to change a class property by putting a const
after the method arguments.)
Upvotes: 3