PHP 7-警告:array_column()期望参数1为数组,给定对象

问题描述 投票:0回答:1

我刚刚在我的项目中发现了一些奇怪的东西。我正在使用PHP7.3,并且尝试对对象使用array_column()函数。

我正在使用命令在symfony项目中调用服务-如果这很重要,但是我已将代码简化到最低限度。

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

我正在尝试以数组的形式获取文章的类别-在这种情况下,我使用以下代码:

$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()一起添加功能

但是这些都不适合我。即使array_column应该可以在PHP> 7中使用对象?感谢您的帮助

php symfony command php-7
1个回答
4
投票

尝试使用private $name

© www.soinside.com 2019 - 2024. All rights reserved.