-3

私は現在、次のようなものを使用しています

class User{

    /* @var Contacts*/
    public $contacts = array();
}

$userObj = new User();
$userObj->contacts[] = new Contact(...);
$userObj->contacts[] = new Contact(...);

phpDocumentor を使用して変数のタイプを文書化することはできませんが、連絡先配列に割り当てられる他のタイプのオブジェクトを制限することも可能ですか?

$userObj->contacts[] = 2.3 //should be considered as invalid
4

2 に答える 2

2

プライベートとして宣言$contactsし、ゲッター メソッドとセッター メソッドを使用します。

Class User{

  private $contacts = array();

  function addContact($contact) {
    if (is_object($contact) && get_class($contact) == "Contact") {
      $this->contacts[] = $contact;
    } else {
      return false;
      // or throw new Exception('Invalid Parameter');  
    }
  }

  function getContacts() {
    return $this->contacts;
  }
}
于 2012-08-29T17:23:14.837 に答える
2

PHPでの動作ではありません

代わりにできることは次のとおりです

class User{

    /* @var Contacts*/
    private $contacts = array();

    public function setContacts(Contact $contact){
        $this->contacts[] = $contacts;
    }
}

いいえ、そのように使用できます

$userObj = new User();
$userObj->setContacts(new Contact(...));

そして、以下はエラーになります

$userObj->setContacts(2.3);
于 2012-08-29T17:24:06.227 に答える