2016-07-19 9 views
0

Wie kann ich auf Eigenschaften in Objekten zugreifen, die in einem Array enthalten sind?Wie kann ich auf Eigenschaften in Objekten zugreifen, die in einem Array enthalten sind - siehe Code

Warum funktioniert der folgende Code nicht?

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

Dank

+2

Go nachschauen, was 'private' Sichtbarkeit bedeutet. – CBroe

Antwort

3

Ihre Syntax und Konstruktor ist falsch.

Hier ist der endgültige 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; 

?> 
+0

Wer hat gewählt, bitte überprüfen Sie die Antwort noch einmal. – activatedgeek

+0

Code funktioniert gut. Vielen dank für Deine Hilfe. –

2

Es gibt mehrere Fehler im Code, ich habe sie mit Pfeilen hingewiesen ◄■■■:

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

Vielen Dank für die Erläuterungen, das hilft. –

Verwandte Themen