2015-05-08 20:30
浏览 34

PHP OOP - 类中的类数组[关闭]

I was wondering how you can define an array of objects within another object.

For example, let's say I have a class called "User", and another class called "Address".

A user can list an unlimited number of addresses. How do I do this?

My guess is that I need to declare an array of "Address" objects within the "User" class, but I am not sure how to do it.

图片转代码服务由CSDN问答提供 功能建议

我想知道如何在另一个对象中定义一个对象数组。 < p>例如,假设我有一个名为“User”的类,另一个名为“Address”的类。

用户可以列出无限数量的地址。 我该怎么做?

我的猜测是我需要在“User”类中声明一个“Address”对象数组,但我不知道该怎么做。< / p>

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • dou760663 2015-05-08 21:00

    Make a class, with a property that is an array, then add to the array:

    class User
        private $addresses = [];
        public function addAddress(Address $address)
            $this->addresses[] = $address;
        public function getAddresses()
            return $this->addresses;
    class Address
        private $street;
        public function __construct($street)
            $this->street = $street;
            // ... etc
    $user = new User();
    $user->addAddress(new Address("Foo"));
    $user->addAddress(new Address("Bar"));
    解决 无用
    打赏 举报

相关推荐 更多相似问题