У меня есть страница 'player.php', где у меня есть объект player и функции этой и другой страницы 'index.php', где отображается небольшая форма, где добавляется имя игрока и создается новый игрок.
Если я размещу весь код на странице player.php, он будет работать правильно, добавьте в проигрыватель и в кнопке списка отобразится каждый созданный проигрыватель.
Но так как он у меня отдельно, он не работает, я добавил include ("player.php"), но он все равно не работает.
player.php
<?php
session_start();
class Player {
private $players;
private $name;
public function __construct($name)
{
$this->name = $name;
$this->players = array();
}
public function getName()
{
return $this->name;
}
public function addPlayer($onePlayer)
{
$this->players[] = $onePlayer;
return $this;
}
public function printPlayers()
{
foreach($this->players as $player){
echo $player.'<br />';
}
}
public function __toString()
{
return $this->name;
}
}
function printForm()
{
echo '<FORM METHOD="POST" style="text-align: center; margin-top: 73px;">
<h2>Add Players</h2>
<label>Add the name : </label><INPUT class="form" TYPE = "text" NAME = "name"> <br><br>
<INPUT class="form" TYPE = "submit" VALUE = "add" name="action">
<INPUT class="form" TYPE = "submit" VALUE = "list" name="action">
</ FORM>';
}
// Load the player data of the session and if it does not exist create a new player.
function loadData()
{
return isset($_SESSION['player']) ? $_SESSION['player'] : new Player();
}
// Save the player's data in the session.
function saveData($player)
{
$_SESSION['player'] = $player;
}
/**** If I put the index.php code here it works fine
printForm();
$player = loadData();
if(isset($_POST['action']))
{
switch($_POST['action'])
{
case 'add':
$player->addPlayer(new Player($_POST['name']));
saveData($player);
break;
case 'list':
echo '<hr />';
$player->printPlayers();
break;
}
}
*****/
?>
index.php
<?php
session_start();
include("player.php");
printForm();
$player = loadData();
if(isset($_POST['action']))
{
switch($_POST['action'])
{
case 'add':
$player->addPlayer(new Player($_POST['name']));
saveData($player);
break;
case 'list':
echo '<hr />';
$player->printPlayers();
break;
}
}
?>