Here is a scenario
class page {
public $name;
public $title;
public function showhead() {
return "<head><title>".$this->title."</title></head>";
}
}
$mypage = new page;
$mypage->title = "My Page title";
$mypage->showhead();
and another scenario
class page {
public $name;
public function showhead($title) {
return "<head><title>".$title."</title></head>";
}
}
$mypage = new page;
$mypage->showhead("My Page title");
Among these methods, which is better and which should be avoided? And why?
I guess it depends on whether you need that title ever again. if you do then make property for storage and retrieval. if you only need it that one time then use the method parameter.
There is always some tension between passing parameters around (either individually or in immutable aggregate types, which don't really exist in PHP) and storing them somewhere (be it class properties, globals, whatever). One of the benefits of OOP is that you can store state in objects and benefit from encapsulation (prevents many accidental overwriting of data) while simultaneously avoiding polluting the symbol tables with variables. Using these mutable objects has its own sets of problems, especially if we go into multi-threaded programming, but that's a smaller concern in PHP.
In your particular case, I think it would be a better idea to store the title in the object. As In silico said, it seems to belong to the page
, and on top of that you can do stuff like:
$page = new page;
$page->setTitle("whatever");
...
function doStuff($page) {
...
$page->showhead();
}
And then you don't have to pass $page
together with the title.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With