Seevali H Rathnayake
Seevali H Rathnayake

Reputation: 595

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

Upvotes: 0

Views: 151

Answers (2)

Seevali H Rathnayake
Seevali H Rathnayake

Reputation: 595

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.

Upvotes: 0

Madara&#39;s Ghost
Madara&#39;s Ghost

Reputation: 174947

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

Upvotes: 2

Related Questions