Warning: array_push() expects Parameter 1 to be array, null Given in

Asked

Viewed 3,439 times

3

I want to assign objects to a array with array_push, but it’s making a mistake:

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();
  • 2

    It’s easier to use $this->partidas[] = $partida. It’s faster than using the function array_push and it does the same thing

  • Some of the answers served you, if yes you can accept it ???

2 answers

3

Change your method preencheRodada 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;
}

Reason for Error:

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

  • Thanks a lot guy, it worked, I forgot this " $this-> "

  • :), choose as the correct answer, so you can help other people who have the same problem. abs

2

Jeferson already gave a solution to the problem, but I’m complementing it to comment more specifically on the initial 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 class name not to be used, as when specifying $partidas as a parameter, it is only local scoped. Moreover, it would only make sense to specify this initial parameter if it came from outside the class.

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

public function preencheRodada(Partida $partida)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.