我有什么:
$tom = new Driver;
$bmw = new Car;
$benz = new Car;
我想拥有的内容:
foreach (Car::$all_cars as $car) {
$tom->setRating($car, $rating); // $rating comes from user input
}
问题:
如何实现这个?
约束:
我的想法:
Class Driver {
private $cars;
public function __construct() {
$his->cars = new \stdClass();
foreach (Car::$all_cars as $car) {
$this->cars->$car = NULL;
}
}
public setRating($car, $rating) {
$this->cars->$car = $rating;
}
}
Class Car {
public static $all_cars = array();
public $name;
public function __construct($name) {
$this->name = $name;
self::$all_cars[] = $this->name;
}
}
$bmw = new Car('bmw');
$benz = new Car('benz');
$tom = new Driver;
foreach (Car::$all_cars as $car) {
$tom->setRating($car, $rating); // $rating comes from user input
}
答案 0 :(得分:1)
PHP允许您在任何对象上设置属性,例如
$tom = new StdClass;
$tom->bmw = 95;
同样,只要属性名称是字符串,就可以为属性名称使用变量变量,例如
$car = 'bmw';
$tom = new StdClass;
$tom->$car = 95;
这会将公共财产bmw
放在$tom
上,然后您可以使用
echo $tom->bmw; // prints 95
您不能将对象分配给属性,因为它不是字符串,例如
$car = new Car;
$tom = new StdClass;
$tom->$car = 95;
无法正常工作。您必须向Car对象添加__toString
方法并将名称设置为Car的属性:
Class Car
{
private $name;
public function __construct($name)
{
$this->name = $name;
}
public function __toString()
{
return $this->name;
}
}
因为赋予属性名称是字符串上下文,所以当您尝试在字符串上下文中使用Car实例时,PHP将自动使用Car的name属性。没有合适的方法来从变量名称推断名称,例如,你做不到
$bmw = new Car;
并希望从中获得宝马。名称必须在对象中。
我提供的示例适用于您在https://3v4l.org/TjC89
提供的代码