设置参考';PHP中的s类型

设置参考';PHP中的s类型,php,Php,我目前正在使用类似 class User{ /* @var Contacts*/ public $contacts = array(); } $userObj = new User(); $userObj->contacts[] = new Contact(...); $userObj->contacts[] = new Contact(...); 如果我们可以使用phpDocumentor记录变量的类型,是否也可以限制将其他类型的对象指定给contacts数组

我目前正在使用类似

class User{

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

$userObj = new User();
$userObj->contacts[] = new Contact(...);
$userObj->contacts[] = new Contact(...);
如果我们可以使用phpDocumentor记录变量的类型,是否也可以限制将其他类型的对象指定给contacts数组

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

$contacts
声明为private,并使用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;
  }
}

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

它只是一个数组。。。所以没有。但是你可以用神奇的方法和二传手/传接手来做些事情,也许,来欺骗它。这是一个陈述,不是一个问题。这就是传接手和传接手的作用。当需要控制值时,不要使用公共访问。