I’m writing a program that reads a series of tasks from an XML file and puts them within dynamically generated “task” objects (e.g., task1, task2, task3, task4 etc.).
Each taskXX object has properties (task1->name, for example) that are populated by data in the XML file.
My program runs through the XML file and generates a bunch of objects filled with data. However, I can’t use those objects in the rest of my program.
Why is this the case? I’m pretty sure this has to do with scope but I can’t seem to figure it out. Also, I’m not keen on using the global keyword.
Here’s some of the code:
// -- CODE INSIDE FILE: class_todos.php -- //
class readTodos {
public function loadAll() {
$counter = 0;
$xml = simplexml_load_file("todos.xml");
foreach($xml->task as $task) {
${'task'.$counter} = new Task;
$theTask = ${'task'.$counter};
$theTask -> set('id', $task['id']);
$theTask -> set('name', $task->name);
$theTask -> set('note', $task->note);
// and so on and so on...
counter++;
}
}
}
// -- CODE INSIDE FILE: class_task.php -- //
class Task {
private $id;
private $name;
private $note;
// etc. etc.
public function set($varname,$value) {
$this->$varname = $value;
}
public function get($varname) {
return $this->$value;
}
}
// -- CODE INSIDE FILE: index.php -- //
require_once('class_todos.php');
<ul class="todo-list">
<?php
echo $task0 -> get('name');
// The above statement give the error statement: "Undefined variable: task0"
// I know for sure that $task0 IS defined within the scope of the class "readTodos".
// How do I make the $task0 (and upwards... e.g., task1, task2, task3, etc.)
// available for use in the rest of my program?
?>
</ul>
You can’t use classes that way. The
loadAllmethod should return an array of tasks instead of creating variables. When it creates variables inside the method, it’s scope is limited to that method as therefore, it’s not available outside it. You should also consider making that function static.Instead, use something like this:
Your HTML should then do: