【发布时间】:2018-10-20 23:22:47
【问题描述】:
大家好,我有两个类,用户和购物车,它们对它们之间的二进制关联进行建模。为了实现它,我创建了两个类
一个用户类:
class User{
protected $name ;
protected $email;
protected $shoppingCart;
public function __construct($name , $email)
{
$this->name =$name;
$this ->email =$email;
$this->shoppingCart=new ShoppingCart($this);
}
//other getter and setter functions
}
class ShoppingCart{
//Array stores the list of products in the cart:
protected $products = array();
// For storing the IDs, as a convenience:
protected $ids = array();
// protected user
protected $user;
// Constructor just sets the object up for usage:
function __construct($user) {
$this->products = array();
$this->ids = array();
$this->user =$user;
}
// functions to add or delete item
}
我的问题是,用户类和购物车类是否可以相互拥有一个实例,所以当我构造用户时,我在其构造函数中构造它的购物车。当我构建购物车时,我在购物车构造函数中传递用户信息以将购物车分配给用户。
我怎样才能正确地模拟这种关联。此外,我还必须访问用户购物车以从主 PHP 脚本显示其总价...在这种情况下,我还可以将用户类的 ShoppingCart 属性设为公开
【问题讨论】:
-
ShoppingCart没有理由拥有用户的实例,因为您已经知道它属于哪个用户(因为它在用户对象中)。如果不访问用户对象,您甚至无法访问购物车。