Warning: array_push () expects parameter 1 to be array, null given in

3

I want to assign objects to a array with array_push , but it is giving error:

  Warning: array_push () expects parameter 1 to be array, null given in

My class:

<?php

//PREPARA UMA RODADA    
class Rodada
{
    $partidas = array();

    //PREENCHE O ARRAY
    public function preencheRodada($partidas, Partida $partida)
    {
        array_push($partidas, $partida);
    }   

    //RETORNA O ARRAY DE PARTIDAS
    public function getRodada()
    {
        return $partidas;
    }
}

test class

    require_once('../logica/models/Time.php');
require_once('../logica/models/Partida.php');
require_once('../logica/models/Rodada.php');

$time1 = new Time("SANTOS FC");
$time2 = new Time("BARCELONA FC");

$partida1 = new Partida($time1, $time2);
$partida1->setGolsTime1(2);
$partida1->setGolsTime2(3);

$rodada1 = new Rodada();
$rodada1->preencheRodada($partida1);

$partidasDaRodada = $rodada1->getRodada();
    
asked by anonymous 18.11.2015 / 13:56

2 answers

3

Change your method preencheRodada of the Round class

//PREENCHE O ARRAY
public function preencheRodada(Partida $partida)
{
    array_push($this->partidas, $partida);
}   

Also change your method getRodada

//RETORNA O ARRAY DE PARTIDAS
public function getRodada()
{
    return $this->partidas;
}

Error reason:

The error happens because when you call the method, it is expecting 2 arguments, the first would be the array and the second the match

    
18.11.2015 / 14:00
2

Jeferson has already solved the problem, but I am complementing it to comment more specifically on the root cause of the problem.

Note in the method definition:

public function preencheRodada($partidas, Partida $partida)

The first parameter is $partidas . This causes the variable of the same name of the class not to be used, because specifying $partidas as a parameter, it is only locally scoped. Also, it would only make sense to specify this initial parameter if it were to come from outside the class.

The simplest solution would be to define the method this way:

public function preencheRodada(Partida $partida)
    
12.12.2015 / 01:47