-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为私有并使用 getter 和 setter 方法。

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 回答