简体   繁体   中英

PHP: A Class as a member inside another Class

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 User s (or all Users from the database), I want that all Users to load their own Category.

Of course, you can store a Category object inside of the User 's $category memeber:

$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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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