2013-06-02 127 views
1

有沒有辦法在調用函數時避免太多參數?我這樣做如何在php中調用函數時避免太多參數

Eg: 
function myFunction($usrName,$usrCountry,$usrDOB//and many more){ 
    // Do something with all those arguments here 
} 

的一種方法是定義常量

//After thorough checking 

$sesUserName = $_SESSION['sesUserName']; 

define('USERNAME', $sesUserName); 

myFunction(){ 
    // Do something with USERNAME here 
    // No need to use USERNAME when calling the function 
} 

但是否有其他方法可以做到這一點?

+0

我不會做你在做常量那裏。如果你真的想在'myFunction()'中訪問'$ sesUserName',你可以調用'global $ sesUserName;'作爲'myFunction()'中的第一行。這是一個不變的事情,但它仍然普遍不鼓勵。您也可以在不執行'global'的情況下訪問superglobals(像'$ _SESSION'這樣的'$ _'數組),所以您可以直接從函數內部訪問'$ _SESSION ['sesUserName']''。不過,這可能不是最好的方法。正如其他人指出的那樣,我建議使用關聯數組。 –

+0

他們是必需的。但就像我說的,我不知道用不同的方式來做到這一點。 – Norman

+0

你可以解析一個數組 – 2013-06-02 05:09:26

回答

4

一種方法是開始使用面向對象的程序和創建用戶對象。這將允許您將用戶用作單個實體,而不是任意組的屬性或常量。

<?php 

    class User { 
     public $name; 
     public $country; 
     public $dateOfBirth; 
     // for stuff that a user does or is define as instance methods 
     public function isUserOver18(){ 
      return time() < strtotime("+18 years", strtotime($dateOfBirth)); 
     } 
    } 

    $user = new User(); 
    $user->name = $data["name"]; 
    $user->country = $data["country"]; 
    $user->dateOfBirth = $data["dob"]; 

    if ($user->isUserOver18()){ 
     // show page 
    } else { 
     echo "You must be 18 years or older to view this video"; 
    } 

    // for stuff that is done to a user pass it in as an argument. 

    notifyUser($user, "You've got mail"); 
1

你可以傳遞參數數組:

function myFunction($arrayArgs){ 
    if(is_array(arrayArgs){ 
     if(!array_key_exists('usrName', $arrayArgs)){ 
      return null; 
     } 

     if(array_key_exists('usrCountry', $arrayArgs)){ 
      return null; 
     } 

     //and many other ifs 
    } 
} 
0

是那些PARAMS所有必需的?您可以將1個數組作爲所有必需鍵的參數。

E.g:function myFunc($arr)和陣列將array('user_name' => '', 'user_country' => '',...)

2

而是創建需要你在一噸則params的傳遞巨大的功能。瞭解面向對象編程,並創建一個PHP類。

我保證,一旦你學會了這些技巧,你就會看到完全不同的編程。您可以爲經常執行的操作創建可重用的類,例如數據庫操作,用戶管理系統等等。

掌握使用對象和類是什麼從平庸的程序員分離平庸的程序員。

Here is a good beginner tutorial on object oriented programming in PHP

0

Zend Framework 1.x實際上有很好的處理參數的實現。規則非常簡單。如果您需要3個或更少的參數,只需直接指定它即可。但是,如果您已經需要超過3個參數,則需要將第三個參數作爲一個數組,在調用時您只需指定一組鍵值對值。實際上基於經驗的確很不錯。

相關問題