0

Ive made a Todo class and instance. A todo is created and added to the array:

$allTodos = array();

class Todo {
  public $todo;
}

$newTodo = new Todo();
$newTodo->todo = "Tidy room";
array_push($allTodos, $newTodo);

var_dump($allTodos);

However when I try to put the code into a function it seems to break:

$allTodos = array();

class Todo {
  public $todo;
}

function createTodo() {
  $newTodo = new Todo();
  $newTodo->todo = "Tidy room";
  array_push($allTodos, $newTodo);
}

createTodo();

var_dump($allTodos);

I was calledPHP Warning: array_push() expects parameter 1 tobe array, null given in /home/runner/main.php on line 19 array(0) {

Im learning PHP but my background is JavaScript so not sure if I'm expecting PHP to be behave like JS in way that it doesn't?

Evanss
  • 23,390
  • 94
  • 282
  • 505

1 Answers1

0

Because createTodo() cannot 'see' $allTodos. You'd need to make it available to it via the global command:

function createTodo() {
    global $allTodos; //<-- this
    $newTodo = new Todo();
    $newTodo->todo = "Tidy room";
    array_push($allTodos, $newTodo);
}

That said, globalising variables is frowned on in PHP for various reasons. Alternatively you could pass it in to your function as a reference:

function createTodo(&$arr) { //<-- & denotes by reference, not value
    $newTodo = new Todo();
    $newTodo->todo = "Tidy room";
    array_push($arr, $newTodo);
}
createTodo($allTodos);
Mitya
  • 33,629
  • 9
  • 60
  • 107