Syl*_*llz 1 php command symfony php-7
我刚刚在我的项目中发现了一些奇怪的东西。我正在使用 PHP7.3 并且我正在尝试将该array_column()函数与对象一起使用。
我正在使用一个命令来调用一个 symfony 项目中的服务 - 如果这很重要,但是我已经将我的代码简化为最重要的。
文章.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;
}
}
Run Code Online (Sandbox Code Playgroud)
文章分类.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;
}
Run Code Online (Sandbox Code Playgroud)
我试图将文章的类别作为数组获取 - 在这种情况下,我使用以下内容:
$categories = array_column($a->getCategory(), 'name'); //$a is the article object
但是,这会引发以下警告:
Warning: array_column() expects parameter 1 to be array, object given
我已经尝试过的
private $name公众__get()并__isset()使用private $name然而,这些都不适合我。即使 array_column 应该与 PHP >7 中的对象一起使用?我感谢任何帮助
如果你需要数组使用这个 $categories = $a->getCategory()->toArray();
如果您需要类别名称数组 - 使用数组映射
$categoriesName = $a->getCategory()->map(function(ArticleCategory $category) {
return $category->getName();
});
Run Code Online (Sandbox Code Playgroud)