我現在有2個函數來構造html
來顯示,這取決於數據源; 1是從database
,另一個是從form
post
。概括一個訪問多種類型對象的函數(通過函數和數組)
function buildForm_newUser($user){
$html_username = 'Username = ' . $_POST['username'];
$html_location = 'location = ' . $_POST['location'];
: // similar rows follow more than 20 times
}
function buildForm_exsitingUser($user){
$html_username = 'Username = ' . $user->get_property('username');
$html_location = 'location = ' . $user->get_property('location');
:
}
是否有可能實現這些只有1個功能?
我試着切換源對象(即上面的$user
和$_POST
),但後來因爲後一個函數使用指定對象的功能而被卡住,而前者沒有。另外,因爲有許多行必須訪問任一對象,所以我喜歡在處聲明新生成的變量(上例中爲$ html_ *變量),只有一個位置。這就是說,我想要這樣的事情:
function buildForm($user){ // Number and type of argument can vary
// Do something here to specify object type
$html_username = 'Username = ' . // following here, either $_POST or $user->get_property to get 'username'
$html_location = 'location = ' . // following here, either $_POST or $user->get_property to get 'location'
:
}
謝謝。
(也很欣賞的建議更好的標題......)
+其他20個參數寫成,所以它不是那麼容易,但你的想法沒有錯。 – hakre
對不起,我沒有看過那部分。但我認爲它並不難看:一個表單構造器應該只是建立一個表單,而不關心數據的來源。其實,我認爲在你的功能中加入一些「功能性」智能相關的代碼是錯誤的! – Sebas