I leave this answer done quickly.
Maybe some controls are missing in the class, but seeing as it was an exercise I did not want to get involved with very advanced things.
Class Jugador
In the addPuntos
method there was a design error. A method of adding should not return anything. To know the state of the object use a getter
The purpose of the method is to add points to the object, not return the points you have, for that there is the method getPuntos()
.
class Jugador {
private $numeroJug;
private $ptos;
function __construct($numeroJug) {
$this->numeroJug = $numeroJug;
}
function getNumeroJug() {
return $this->numeroJug;
}
function getPtos() {
return $this->ptos;
}
function addPuntos($ptos){
if($ptos>0){
$this->ptos+=$ptos;
}
// return $sumaPtos; ERROR DE DISEÑO
}
}
Class Equipo
Basically it would be this:
It would have a property called $jugador
of type array
, which would save an array of Jugador
objects passed through the addJugador()
method.
The method getTotal()
calculates the total points of all the players, obtaining them and adding them by means of the method getPuntos
of the object Jugador
.
It can also be verified that the parameter passed to the method is of type Jugador
using instanceof
... That way the method is prevented from receiving anything.
There are more advanced controls that can be used, but that will already depend on you and the requirements you have.
class Equipo{
private $jugador=array();
function __construct() {
}
function addJugador($unJugador){
if ($unJugador instanceof Jugador) {
$this->jugador[]=$unJugador;
}
}
function getTotal(){
$total=0;
foreach($this->jugador as $arr) {
$total+=$arr->getPtos();
}
return $total;
}
}
Test code
VIEW COMPLETE DEMO IN REXTESTER
We are going to test our code.
/*Código de prueba*/
$unJugador=new Jugador(1);
$otroJugador=new Jugador(7);
$unJugador->addPuntos(50);
$unJugador->addPuntos(3);
$otroJugador->addPuntos(27);
$elEquipo=new Equipo();
$elEquipo->addJugador($unJugador);
$elEquipo->addJugador($otroJugador);
$totalPuntos=$elEquipo->getTotal();
echo "Total de puntos: ".$totalPuntos;
echo PHP_EOL;
/*Viendo un Jugador por dentro*/
var_dump($unJugador);
/*Viendo el Equipo por dentro*/
var_dump($elEquipo);
Exit:
For the total points:
Total de puntos: 80
Object Jugador
:
object(Jugador)#1 (2) {
["numeroJug":"Jugador":private]=>
int(1)
["ptos":"Jugador":private]=>
int(53)
}
Object Equipo
:
object(Equipo)#3 (1) {
["jugador":"Equipo":private]=>
array(2) {
[0]=>
object(Jugador)#1 (2) {
["numeroJug":"Jugador":private]=>
int(1)
["ptos":"Jugador":private]=>
int(53)
}
[1]=>
object(Jugador)#2 (2) {
["numeroJug":"Jugador":private]=>
int(7)
["ptos":"Jugador":private]=>
int(27)
}
}
}