doulei2100 2013-03-28 18:38
浏览 18
已采纳

PHP:一个类作为另一个类中的成员

In my PHP project, I have 2 classes named User & Category as follows.

class User{
    public $Id;
    public $Name;
    public $Category;   
}

class Category{
    public $CategoryId;
    public $CategoryName;
}

My requirement is to include both CategoryId & CategoryName inside the $Category of the User when retrieving data.

So when I accessing a User - object I can get both CategoryId & CategoryName of the user.

Thanks.

UPDATE

How to automate this process? When I want to load a User from the database, I want that User to load it's Category details Automatically.

And when I loading a collection of Users (or all Users from the database), I want that all Users to load their own Category.

  • 写回答

2条回答 默认 最新

  • dsgffz2579 2013-04-04 06:58
    关注

    This is the solution that I wanted.

    // user.php
    <?php
    require_once 'category.php';
    
    class User{
        public $Id;
        public $Name;
        public $Category;   
    
        public function __construct(){
            $this->Category=Category::getCategory($this->Id);       
        }
    }
    ?>
    
    // category.php
    <?php
    class Category{
        public $CategoryId;
        public $CategoryName;
    
        public static function getCategory($UserId){
            $Category = //PDO operations;
            return $Category;
        }
    }
    ?>
    

    Thanks for everyone who replied.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置