0

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

1
  • 2
    Go look up what private visibility means. Commented Jul 19, 2016 at 14:21

2 Answers 2

3

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;

?>
Sign up to request clarification or add additional context in comments.

1 Comment

Whoever has down voted, please check the answer again.
2

There are multiple errors in your code, I have pointed them with arrows ◄■■■ :

<?php

class Car{
    public $model;   //◄■■■■■■■■■■ IF PRIVATE YOU WILL NOT
    public $color;   //◄■■■■■■■■■■ BE ABLE TO ACCESS THEM
    public $price;   //◄■■■■■■■■■■ FROM OUTSIDE.
    public function __construct ($model, $color, $price) //◄■■■ CONSTRUCT
    {
        $this->model = $model;   //◄■■■■■■■■■■■■■■■■■■■■■■■ NOT THIS.$
        $this->color = $color;   //◄■■■■■■■■■■■■■■■■■■■■■■■ NOT THIS.$
        $this->price = $price;   //◄■■■■■■■■■■■■■■■■■■■■■■■ NOT THIS.$
    }
}

$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;   //◄■■■■■■■■■■■■■■■■■■ PUBLIC PROPERTY WITHOUT $.
echo $cars[0]->color;   //◄■■■■■■■■■■■■■■■■■■ PUBLIC PROPERTY WITHOUT $.
echo $cars[0]->price;   //◄■■■■■■■■■■■■■■■■■■ PUBLIC PROPERTY WITHOUT $.
?>

1 Comment

Thanks a lot for the explanation-comments, that helps.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.