如何访问数组中包含的对象的属性?
为什么下面的代码不起作用?
<?php
class Car{
private $model;
private $color;
private $price;
public function __car($model, $color, $price)
{
this.$model = $model;
this.$color = $color;
this.$price = $price;
}
}
$cars = [];
$jetta = new Car("Jetta", "Red", 2500);
$cars[] = $jetta;
$cobalt = new Car("Cobalt", "Blue", 3000);
$cars[] = $cobalt;
// this is the part of the code that doesn't work
// I need to output the values from the objects, model, color and price
echo $cars[0]->$model;
echo $cars[0]->$color;
echo $cars[0]->$price;
由于
答案 0 :(得分:3)
您的语法和构造函数是错误的。
以下是最终代码:
<?php
class Car{
// the variables should be public
public $model;
public $color;
public $price;
// this is how you write a constructor
public function __construct($model, $color, $price)
{
// this is how you set instance variables
$this->model = $model;
$this->color = $color;
$this->price = $price;
}
}
$cars = [];
$jetta = new Car("Jetta", "Red", 2500);
$cars[] = $jetta;
$cobalt = new Car("Cobalt", "Blue", 3000);
$cars[] = $cobalt;
// this is how you access variables
echo $cars[0]->model;
echo $cars[0]->color;
echo $cars[0]->price;
?>
答案 1 :(得分:2)
您的代码中存在多个错误,我用箭头myBucketEndpointName
指出了它们:
port 22: Connection timed out