设置引用';s在PHP中的类型


Setting a reference's type in PHP

我目前正在使用类似的东西

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

不是它在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);

$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;
  }
}