简体   繁体   English

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

[英]PHP: A Class as a member inside another Class

In my PHP project, I have 2 classes named User & Category as follows. 在我的PHP项目中,我有两个名为UserCategory ,如下所示。

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. 我的要求是在检索数据时在User$Category中包含CategoryIdCategoryName

So when I accessing a User - object I can get both CategoryId & CategoryName of the user. 因此,当我访问User - object我可以获得用户的CategoryIdCategoryName

Thanks. 谢谢。

UPDATE 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 . 当我想从数据库加载User ,我希望该User 自动加载它的Category详细信息。

And when I loading a collection of User s (or all Users from the database), I want that all Users to load their own Category. 当我加载User的集合(或数据库中的所有用户)时,我希望所有用户都加载他们自己的类别。

Of course, you can store a Category object inside of the User 's $category memeber: 当然,您可以在User$category memeber中存储Category对象:

$user = new User;
$cat = new Category;

$cat->categoryId = 42;
$cat->categoryName = "Meaning of Life";

$user->category = $cat;

//access
echo $user->category->categoryName; //Meaning of Life

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. 感谢所有回复的人。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM