Objekt aus Array auslassen

DerEisige

Erfahrenes Mitglied
Hallo,
ich habe ein Objekt in einem Array gespeichert und möchte es nun auslesen, wenn ich das Objekt nun aber aufessen will, crasht das Scrip.

PHP:
$game = new Board();

class Board {
    private $fieldTyp = array();
    
    public function __construct(){
        $this->createStandardFieldTyp();
    }
    
    private function createStandardFieldTyp() {
        echo "Stard:  createStandardFieldTyp <br />";
        
        $this->fieldTyp[] = new FieldTyp("Holz", "br", true);
        $this->fieldTyp[] = new FieldTyp("Wüste", "de", false);
        $this->fieldTyp[] = new FieldTyp("Lehm", "or", true);
        $this->fieldTyp[] = new FieldTyp("Schaff", "sh", true);
        $this->fieldTyp[] = new FieldTyp("Getreide", "wh", true);
        $this->fieldTyp[] = new FieldTyp("Holz", "wo", true);
        
        for($i=0; $i < count($this->fieldTyp); $i++){
            echo count($this->fieldTyp);
            echo $this->fieldTyp[i]::toString(). "<br />"; ### Fehler##########
        }
    }
}

class FieldTyp{
    private $name;
    private $number;
    private $cod;
    
    public function __construct( $name, $cod, $number){
        $this->name = $name;
        $this->number = is_bool($number);
        $this->cod = $cod;
        echo "add FieldType".$this->toString()."<br>";
    }
    
    public function getAll() {
        return array($this->name, $this->cod, $this->number);        
    }
    public function getName() {
        return $this->name;
    }
    public function getNumber() {
        return $this->number;
    }
    public function getCod() {
        return $this->cod;
    }
    
    public function toString() {
        return $this->name.", ".$this->number.", ".$this->cod;
    }
}
 
Zunächst fehlt da das $ in der echo-Anweisung wo der Fehler auftritt. Korrigiere ich das, bekomme ich folgende Fehler:
Deprecated: Non-static method FieldTyp::toString() should not be called statically
Fatal error: Uncaught Error: Using $this when not in object context
D. h. Du musst die Methode nicht statisch sondern im Objekt-Kontext, mit Pfeil, aufrufen:
Code:
echo $this->fieldTyp[$i]->toString() . "<br />";
 
Zuletzt bearbeitet:

Neue Beiträge

Zurück