在我的PHP项目中,我有2个名为User
&Category
的类,如下所示。
class User{
public $Id;
public $Name;
public $Category;
}
class Category{
public $CategoryId;
public $CategoryName;
}
我的要求是在检索数据时将CategoryId
和CategoryName
包含在User
的$Category
中。
因此,当我访问User - object
时,我可以同时获得用户的CategoryId
和CategoryName
。
谢谢。
更新
如何自动化此过程?当我想从数据库中加载User
时,我希望该User
自动加载它Category
详细信息。
当我加载User
集合(或数据库中的所有用户(时,我希望所有用户都加载自己的类别。
当然
,你可以将Category
对象存储在User
的$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
这就是我想要的解决方案。
// 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;
}
}
?>
感谢所有回复的人。