2016-12-14 97 views
1

我怎樣才能創建一個對象在PHP(如C#)PHP7對象集合+性能

用於爲例用戶與3個屬性

class Users 
{ 
    private $name; 
    private $age; 
    private $sex; 

    public function __construct($name, $age, $sex) { 
     $this->name = $name; 
     $this->age = $age; 
     $this->sex = $sex; 
    } 
} 

我怎麼可以添加用戶集合 中,然後循環用戶收集得到

$user->name 
$user->age 
$user->sex 

謝謝

+0

這是一個關於[基本文檔](http://php.net/manual/en/language.oop5.basic.php)的問題。 PHP7也實現*匿名類*。類似的方法是*關聯數組*。 –

+0

謝謝,但我找不到它,我發現只有數組key =>值的集合。 我想創建具有> 2屬性的對象集合,而不僅僅是鍵值 –

+0

值可以是一切,也可以是對象和數組。這是一個語法問題。 '$ obj-> propname'與'$ arr ['itemname']''。您的問題針對哪個PHP版本?協會。數組集合:'for($ i = 0; $ i

回答

0

從你的連鎖行業例如,它可能是這樣實現的:

class User 
{ 
    const 
    SEX_M = 1, 
    SEX_F = 2 
    ; 

    private 
    $name, 
    $age, 
    $sex 
    ; 

    public function __construct($name, $age, $sex) { 
    $this->name = $name; 
    $this->age = $age; 
    $this->sex = $sex; 
    } 

    public function dump() 
    { 
    echo "name: $this->name, age: $this->age, sex: " 
     . ($this->sex === User::SEX_M ? 'm' : 'f') . "<br>\n"; 
    } 
} 

$collection = array(); 
$collection[] = new User('Tom' , 10, User::SEX_M); 
$collection[] = new User('Jerry', 11, User::SEX_F); 

foreach ($collection as $user) 
    $user->dump(); 
+0

完美!正是我想要的, 非常感謝 –

+0

@ErickBoileau你甚至可以在年輕的PHP版本中使用標量類型提示。例如'public function __construct(string $ name,int $ age,int $ sex){' –

+0

謝謝,我已經習慣了C#和很新的php –