$temp
是一個對象,而不是一個類,並且您不能在現有對象上使用new
關鍵字。
$plain = 'PlainPiza';
$seafood = 'SeaFood';
$mashrooms = 'Mashrooms';
$piza = new $mashrooms(new $seafood(new $plain)));
鑑於新的信息
The problem is I don't know how many classes I will instantiate
我覺得你的做法我是錯的。你有沒有想過有一個比薩類和添加您的頂部對象比薩餅對象?例如:
<?php
class Pizza
{
private $_toppings;
private $_placements = array('left', 'right', 'whole');
public function _construct()
{
foreach($this->_placements as $placement)
{
$this->_toppings[$placement] = array();
}
}
public function add_topping(Base_Topping $topping, $placement)
{
if(in_array($placement, $this->_placements))
{
array_push($this->_toppings[$placement], $topping);
}
}
}
abstract class Base_Topping
{
protected $_price = 0.00;
protected $_name = 'No Name';
public function get_name()
{
return $this->_name;
}
public function get_price()
{
return $this->_price;
}
}
class Mushrooms extends Base_Topping
{
protected $_price = '1.00';
protected $_name = 'Mushrooms';
}
// assuming $_POST['toppings'] = array('Mushrooms' => 'whole', 'Pepperoni' => 0, 'Sausage' => 0, etc...)
$pizza = new Pizza();
$toppings = array_filter($_POST); // will return anything with a non-false value
foreach($toppings as $name => $coverage)
{
$topping = new $name();
$pizza->add_topping($topping, $coverage);
}
?>
爲什麼你需要做的是什麼? – jszobody
這只是在PHP中用於實例化對象的語法... –
我正在使用裝飾器設計模式。我希望用戶選擇頂部並相應地計算價格。 – user3087969