Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should passing parameter in method be avoided and used as much as possible in OOP?

Tags:

oop

php

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?

like image 736
Starx Avatar asked Jul 04 '10 07:07

Starx


2 Answers

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.

like image 99
spinon Avatar answered Oct 01 '22 01:10

spinon


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.

like image 22
Artefacto Avatar answered Sep 30 '22 23:09

Artefacto