タイトルが理にかなっていることを願っています.PHPクラスの使用を学んでおり、かなりよく理解しています.読んだ/見たチュートリアルを超えて、配列を使用して値を返すようにしています.
私は純粋に実験しているだけで、なぜ私がやっていることは間違っているのか知りたいと思ってgetTheGameType()
います.
//Just a manual array containing key/value pairs of games with their genres
$array = array(
"Grand Theft Auto" => "Action",
"NBA 2k14" => "Sports",
"COD" => "Shooting",
);
//My object
class videoGames {
public $title;
public $genere;
public function setTheGameType($title,$genere) {
$this->title = $title;
$this->genere = $genere;
}
public function getTheGameType() {
return 'The game genre for '.$this->title.' is:' . $this->genere;
}
}
//New instance of `videoGames` class
$list = new videoGames();
//Here I set the game title with its genere
foreach ($array as $title => $genere) {
$list-> setTheGameType($title,$genere);
}
//Echo the value passed into getTheGameType() function
echo $list->getTheGameType();
上記は COD のゲーム ジャンルを返します: 配列の最後の値を取得するシューティング..
getTheGameType()
基本的にメソッドをループしているすべてのキーと値のペアを返すにはどうすればよいですか?
編集: foreachループに追加することで機能し ました。echo $list->getTheGameType();
メソッドへの質問?これは悪い習慣ですか?
foreach ($array as $title => $genere) {
$list-> setTheGameType($title,$genere);
echo $list->getTheGameType();
}