我不能100%确定,但这是定义属性的正确方法吗:
class Product {
public $id;
public $name;
}
class LineItem {
public Product $product; //<------ this property
public $qty;
}
或者,最好将其保留为没有类型标识符的$product
吗?
产品应该这样定义:
public $product;
并将其创建为:
$product = new Product();
正如@Jon在评论中所建议的那样。PHP实际上并不支持类型标识符。这是最好的方法(或者至少我会这么做)。只需定义$product
,然后创建构造函数,在该类变量中实例化一个新的Product对象。或者只需在需要时通过LineItem类中的getter/setter方法传入对象。
edit:它确实与情况不同(你没有给出情况,所以我试着猜测并给出一个例子)。
施工单位:
public function __construct($product = new Product()) {
$this->product = $product;
}
Getter/setter的工作方式与相同
public function getProduct() {
return $this->product;
}
//In arguments you're able to make sure it is of a class Product if I'm correct.
public function setProduct(Product $product) {
$this->product = $product;
//You might do a return of $this, dependent on your logic of course.
return $this;
}
编辑:为未来可能受益的用户添加了以下代码。在常规PHP文件中,您可以执行以下操作:
$product = new Product();
//Set some price, description or something in your product...
//Pass product with constructor.
$lineItem = new LineItem($product);
//Get the product of the lineItem...
$product = $lineItem->getProduct();
//Set a product if constructor hasn't been used...
$lineItem->setProduct($product);
正如Jon所说,PHP中不能有类型标识符。
您可以执行类似操作,并使用instanceof
运算符:
class LineItem {
protected $_product;
//...
public function setProduct($p) {
if($p instanceof Product) {
$this->_product = $p;
} else {
throw new Exception("...");
}
}
}
您可以在__construct()
:上使用类型提示
class Product {
public $id;
public $name;
}
class LineItem {
public function __construct(Product $product) {
$this->product = $product;
}
public $qty;
}
您可以在构造函数中设置它
class Product {
public $id;
public $name;
}
class LineItem {
public $product;
public $qty;
function __construct(){
$this->product = new Product();
}
}