Tommy Tommy - 1 month ago 8
PHP Question

PHP Object Oriented array not being printed

Alright so I got 2 problems on my hands at the moment and those are


  • I want to call the function from the parent object but I am getting a lot of errors saying "Fatal error: Cannot instantiate abstract class Person"

  • If I call the getUserItems directly it will not do anything. There wont be anything echoed or such.






<?php

abstract class Person {
abstract function getUserItems();
}

class inventory extends Person {

protected $storage = array();
protected $item_id;

public function itemAdd($itemname) {
$storage[$this->item_id+1] = $itemname;
}

public function getUserItems() {
foreach($this->storage as $itemName=>$item_id) {
echo $itemName." ".$item_id."<br/>";
}
}
}

$user = new Person();

$user->getUserItems();

/*$user = new inventory();
$user->itemAdd("Item 1");
$user->itemAdd("Item 2");

$user->getUserItems();*/

?>

Answer

In OOP - abstract class may not be instantiated.

An abstract class is a class with both implementation and interface (pure virtual methods) that will be inherited. Interfaces generally do not have any implementation but only pure virtual functions.

So you cannot instantiate (new Person()). You must extend this abstract class and implement it's abtract functions (same way you did in inventory).

Regarding the echoing problem - inside your itemAdd function you didn't use the object's $storage member (you just used a local $storage variable). You should use it as the object's memebr, using $this->storage:

public function itemAdd($itemname) {
    $this->storage[$this->item_id+1] = $itemname;
}

Note that I'm not so sure how you managed the $this->item_id member because you didn't set/changed it in the code.

If you only want to add new items to the storage member you could use:

$this->storage[] = $itemname;

This will make sure every new item will be added to the $storage array.

Comments