2016-07-19 13 views
0

配列に含まれるオブジェクトのプロパティにアクセスするにはどうすればよいですか?配列に含まれるオブジェクトのプロパティにアクセスする方法 -

なぜ以下のコードが機能しないのですか?

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

おかげ

+2

Goが 'private'視認性が何を意味するのか調べます。 – CBroe

答えて

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; 

?> 
+0

落札者の方は、もう一度回答を確認してください。 – activatedgeek

+0

コードは正常に動作します。あなたの助けに感謝します。 –

2

、私は矢◄■■■でそれらを指摘している:

<?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 $. 
?> 
+0

説明のためにありがとう - コメント、それは役立ちます。 –

関連する問題