我有三个php类。我可以这样实例化它们:
$piza = new Mashrooms(new SeaFood(new PlainPiza()));
但是,当我尝试以这种方式动态实例化它们时:
$temp = Mashrooms(new SeaFood(new PlainPiza()));
$piza = new $temp;
失败并显示此错误:
致命错误:Class'SeaFood(找不到新的Mashrooms。
我们将不胜感激。
答案 0 :(得分:1)
$temp
是一个对象,而不是一个类,您不能在现有对象上使用new
关键字。
$plain = 'PlainPiza';
$seafood = 'SeaFood';
$mashrooms = 'Mashrooms';
$piza = new $mashrooms(new $seafood(new $plain)));
鉴于新信息
问题是我不知道我将实例化多少个类
我认为你的方法我错了。您是否考虑过使用Pizza课程并将您的顶级对象添加到披萨对象中?例如:
<?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);
}
?>
答案 1 :(得分:0)
这将有效:
$temp = "Mashrooms";
$pizza = new $temp(new SeaFood(new PlainPiza()));