fs_tigre fs_tigre - 4 months ago 7
PHP Question

How can I access properties in objects contained in an array - see code

How can I access properties in objects contained in an array?

Why does the code below doesn't work?

<?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;


Thanks

Answer

Your syntax and constructor is wrong.

Here is the final code:

<?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;

?>
Comments