I’m currently learning php, and I’m testing out oop and classes.
My code is:
<?php
require('user.php');
$user = new User($username);
$projects = $user->getProjects();
for ($n = 0; $n<count($projects); $n++) {
echo "<li>";
echo "<a id=\"menu_pages\" href=\"\"><img src=\"../images/types/project.png\"/>" . $projects[$n]->name . "</a>";
echo "<ul>";
$items = $user->getItems($n);
for ($i = 0; $i<count($items); $i++) {
echo "<li><a href=\"../\"><img src=\"../images/types/" . $items[$i]->type . ".png\"/>" . $items[$i]->name . "</a></li>";
}
echo "</ul>";
echo "</li>";
}
?>
and I’m getting the error:
Fatal error: Cannot redeclare class Item in /home/ios/public_html/classes/item.php on line 2
I found that its because I’m using
$items = $user->getItems($n);
in a loop. Because if I change it to
$items = $user->getItems(1);
it works. I cannot really figure out anyway of getting around the error.
Help please 🙂
Thanks in advance.
The methods:
function getItems($parent,$type = NULL) {
$items = array();
$username = $this->uname;
$userid = $this->getId($username);
include('classes/config.php');
if ($type != NULL) {
}
require_once('classes/item.php');
foreach ($pdo->query($sql) as $row) {
$instance = new Item();
$instance->name = $row['name'];
$instance->id = $row['id'];
$instance->type = $row['type'];
$instance->parent_id = $row['parent_id'];
$items[] = $instance;
unset($instance);
}
function getProjects() {
$projects = array();
$username = $this->uname;
$userid = $this->getId($username);
include('classes/config.php');
require_once('classes/project.php');
foreach ($pdo->query($sql) as $row) {
$proj = new Project();
$proj->name = $row['name'];
$proj->id = $row['id'];
$projects[] = $proj;
unset($proj);
}
return $projects;
}
edit:
its still not working with changing it. The code goes through with no errors, but now what should be under the first is under the second and the first is blank. See any issues in my logic?
Use
require_oncewhile including files with classes definition (I guess this will be somewhere ingetItems()) or organize your files and define magic function __autoload() that will load it for you when used.After looking into provided source, I doubt that this works for more than one row…
Here you create instance of
Itembefore even checking if there are any items, and after first loop$instanceis destroyed:This should look like:
So for every item new instance is created.