Reputation: 340
I just found something weird in my project. I am using PHP7.3 and I am trying to make use of the array_column()
function with objects.
I am using a command to call a service in a symfony project - if that matters, however I have simplified my code to the minimum important.
Article.php:
class Article {
private $id;
private $category;
public function __construct()
{
$this->category = new ArrayCollection();
}
public function getCategory(): Collection
{
return $this->category;
}
public function addCategory(ArticleCategory $category): self
{
if (!$this->category->contains($category)) {
$this->category[] = $category;
}
return $this;
}
public function removeCategory(ArticleCategory $category): self
{
if ($this->category->contains($category)) {
$this->category->removeElement($category);
}
return $this;
}
}
ArticleCategory.php
class ArticleCategory
{
private $id;
private $name;
public function getName(): ?string
{
return $this->name;
}
public function setName(string $name): self
{
$this->name = $name;
return $this;
}
I am trying to get the categories of an article as an array - for this case I use following:
$categories = array_column($a->getCategory(), 'name'); //$a is the article object
However this throws following warning:
Warning: array_column() expects parameter 1 to be array, object given
What I already tried
private $name
public__get()
and __isset()
with private $name
However none of this works for me. Even though array_column should work with objects in PHP >7 ? I appreciate any help
Upvotes: 1
Views: 6668
Reputation: 2561
If you need array use this $categories = $a->getCategory()->toArray();
If you you need array of category names - use array map
$categoriesName = $a->getCategory()->map(function(ArticleCategory $category) {
return $category->getName();
});
Upvotes: 7