Php 使用collect函数创建的Laravel集合未在私有属性上添加筛选器
我在$contacts上使用了collect(array)函数来转换为collection,并使用where条件根据contactId的条件查找对象Php 使用collect函数创建的Laravel集合未在私有属性上添加筛选器,php,laravel,Php,Laravel,我在$contacts上使用了collect(array)函数来转换为collection,并使用where条件根据contactId的条件查找对象 class Contact { private $contactId; private $name; private $email; public function __construct($contactId, $name, $email) { $this->contactId = $c
class Contact {
private $contactId;
private $name;
private $email;
public function __construct($contactId, $name, $email) {
$this->contactId = $contactId;
$this->name = $name;
$this->email = $email;
}
public function setContactId($contactId) {
$this->contactId = $contactId;
return $this;
}
public function getContactId() {
return $this->contactId;
}
public function setName($name) {
$this->name = $name;
return $this;
}
public function getName() {
return $this->name;
}
public function setEmail($email) {
$this->email = $email;
return $this;
}
public function getEmail() {
return $this->email;
}
}
$contacts = [];
$contacts[] = new Contact(1, "contact 1", "contact1@test.com");
$contacts[] = new Contact(2, "contact 2", "contact2@test.com");
$contacts[] = new Contact(3, "contact 3", "contact3@test.com");
我在$contacts上使用了collect(array)函数来转换为集合,并使用where条件来查找对象。
但它返回空值
$contact = $contacts->where('contactId', 1)->first()
我发现在将contactId属性更改为“public”访问时,我从查询中获得了对象
Contact {#347
+contactId: 1
-name: "contact 1"
-email: "contact1@test.com"
}
我仍然不明白为什么集合不能访问private属性,它应该通过属性的getter来访问它。如果我更改属性访问,最可能的是我反对封装。私有属性的全部要点是,没有人可以在类外访问它。因此,只能从外部访问public。当您使用laravel collection时,可以使用filter并在getter函数上提供条件
collect($contacts)->filter(function ($q){
return $q->getContactId()==1;
});
或者如果你只想要第一个
collect($contacts)->filter(function ($q){
return $q->getContactId()==1;
})->first();