2015-07-20 109 views
-1

是否有可能改變這樣的$email, $firstname, $lastname, $gender喜歡的東西$this->email, $this->firstname一個陣列,更像是一個循環,所以我只需要填寫的第一陣列和陣列之後僅僅能夠使用$this->emailPHP OOP改變可變

+1

你爲什麼不簡單地寫一個類並將類成員(email,firstname等)填充到'__construct()'函數中? – DonCallisto

+0

使用對象並定義getter和setter類以與內部數組進行交互(如果需要)。 – Fluffeh

+1

'$ object =(object)array('email'=> $ email,'firstname'=> $ firstname,'lastname'=> $ lastname,'gender'=> $ gender);'....但是使用'$ this'只適用於類內的方法 –

回答

3

是的,這是可能的,看看這個類:

Class MyClass { 

    public function __construct($myArray){ 
     foreach($myArray as $key => $value){ 
      $this->{$key} = $value; 
     } 
    } 
} 

$array = array(
    "email" => "[email protected]", 
    "firstname" => "John", 
    "lastname" => "Doe", 
    "gender" => "male" 
); 

$class = new MyClass($array); 

如果你做一個var_dump($class)它會告訴你它們的值的屬性。

+0

謝謝你哥們:) – mrfloden

0

如果您只是想將標量變量放入CLASS中,那麼已經在PHP中定義了一個名爲stdClass的類。我想你精神疾病類作爲您使用的->

所以不是加載數據的一個標量變量,你可以做

$user = new stdClass(); 
$user ->email = $_POST['email']; 
$user ->firstname = $_POST['firstname']; 
$user ->lastname = $_POST['lastname']; 
$user ->gender = $_POST['gender']; 

然後,您可以參考使用foreach全班圍繞每一個單獨爲$user ->$email也環

foreach ($user as $field => $value) { 
    echo $field . ' contains the value ' . $value; 
} 

當然,你應該先清理$ _POST。