GEt data from array object - php

Hi i'm new to PHP and have below problem. i have written below codes to add data in to the array, now i need to see the added data, please tell me how to do it.
class ShoppingCart
{
private $items = array();
private $n_items = 0;
function addItem( Item $item )
{
$this->items[] = $item;
$this->n_items = $this->n_items + 1;
//print_r (array_values($this->items));
echo "item $this->items added sussesfully";
}
}
and
class Item {
protected $name;
protected $price;
public function __construct($name, $price) {
$this->name = $name;
$this->price = $price;
}
public function getName() {
echo "item is $this->name";
return $this->name;
}
public function getPrice() {
return $this->price;
}
}
and
require_once('AddingMachine.php');
require_once('item.php');
//$arrayofnumbers = array(100,200);
$objectname = new ShoppingCart();
$objectname->addItem(new Item('My Super Cool Toy', 10.99));
Thanks

Since $items is a private property you will need to create a new method on the ShoppingCart class
public function getItems()
{
return $this->items;
}
And then retrieve the $items array by calling the new method
$objectname = new ShoppingCart();
$items = $objectname->getItems();
var_dump($items);

Related

Php object array (get() method not working)

I'm trying to create an object array but I have several problems.
First I can't use $item= array() in ItemModel class function without making it global.
Second I`m getting array with some weird values back.
I`m new to programming, can someone explain me what am I doing wrong?
class ItemModel{
private $item= array();
public function setItems(){
global $item;
$test = new Bmw("test....", "BMW", 32, 1, 120);
$item[] = $test;
}
public function getItems(){
global $item;
return $item;
}
}
abstract class Car{
private $id;
private $model;
private $price;
private $carTypeId;
public function __construct($id, $model, $price, $carTypeId){
$this->$id= $id;
$this->$model= $model;
$this->$price = $price;
$this->$carTypeId = $carTypeId;
}
public abstract function getAdditionalInfo();
public function getId(){
return $this->$id;
}
public function getmMdel(){
return $this->$model;
}
}
class Bmw extends Car{
private $weight;
public function __construct($id, $model, $price, $carTypeId, $weight) {
parent::__construct($id, $model, $price, $carTypeId);
$this->$weight= $weight;
}
public function getAdditionalInfo(){
return "Weight: ".$this->$weight;
}
}
class ItemView extends ItemModel{
public function showItems(){
$this->setItems();
foreach ($this->getItems() as $item) {
print_r($item);
}
die;
}
}
$test = new ItemView();
$test->showItems();
Results:
Bmw Object
(
[weight:Bmw:private] =>
[id:Car:private] =>
[model:Car:private] =>
[price:Car:private] =>
[carTypeId:Car:private] =>
[test....] => test....
[BMW] => BMW
[32] => 32
[1] => 1
[120] => 120
)
When I try to use function getId() by changing
foreach ($this->getItems() as $item) {
print_r($item->getId());
}
I get
PHP Warning: Undefined variable $id in /workspace/Main.php on line 43
PHP Warning: Undefined property: Bmw::$ in /workspace/Main.php on line 43
I did try to refactor your code and add some comments what I changed and why.
You already did some great work. I think your problem was to use global and not really knowing the syntax of php classes.
<?php
// I did remove the ItemModel Class because it looks like this should be your main code
// see at the end how we add an item from the main code
abstract class Car {
private $id;
private $model;
private $price;
private $carTypeId;
public function __construct($id, $model, $price, $carTypeId){
// when u want to access properties, you dont need specify the property with the dollar sign
$this->id = $id;
$this->model = $model;
$this->price = $price;
$this->carTypeId = $carTypeId;
}
public abstract function getAdditionalInfo();
public function getId(){
return $this->id;
}
public function getModel(){
return $this->model;
}
}
class Bmw extends Car {
private $weight;
public function __construct($id, $model, $price, $carTypeId, $weight) {
parent::__construct($id, $model, $price, $carTypeId);
$this->weight = $weight;
}
public function getAdditionalInfo(){
return "Weight: ".$this->weight;
}
}
// your ItemView class ist just a handler to store multiple items and get them back
// you also dont need to use global $item here, because you want to access the property of the current object
// when you have multiple ItemView objects it would really bug "hungry" :)
class ItemView {
private $items = array();
public function addItem($item){
$this->items[] = $item;
}
public function getItems(){
return $this->items;
}
}
// at the end it is just your items been stored in ItemView and then later getting accessed
$test = new ItemView();
$test->addItem(new Bmw("test....", "BMW", 32, 1, 120));
foreach($test->getItems() as $item) {
print_r($item);
}
// die for whatever reason
die();
You can find and run code here
<?php
class ItemModel{
private $item = array();
public function setItems($item){
$this->item[] = $item;
}
public function getItems(){
return $this->item;
}
public function getItemsAsArray(){
$arrayitem = array();
$arrayitems = array();
foreach ($this->item as $item) {
$arrayitem['ID'] = $item->getId();
$arrayitem['Model'] = $item->getModel();
$arrayitem['Price'] = $item->getPrice();
$arrayitem['TypeID'] = $item->getcarTypeId();
$arrayitem['Info'] = $item->getAdditionalInfo();
$arrayitems[] = $arrayitem;
}
return $arrayitems;
}
}
abstract class Car{
private $id;
private $model;
private $price;
private $carTypeId;
public function __construct($id, $model, $price, $carTypeId){
$this->id = $id;
$this->model = $model;
$this->price = $price;
$this->carTypeId = $carTypeId;
}
public abstract function getAdditionalInfo();
public function getId(){
return $this->id;
}
public function getModel(){
return $this->model;
}
public function getPrice(){
return $this->price;
}
public function getcarTypeId(){
return $this->carTypeId;
}
}
class Bmw extends Car{
private $weight;
public function __construct($id, $model, $price, $carTypeId, $weight) {
parent::__construct($id, $model, $price, $carTypeId);
$this->weight = $weight;
}
public function getAdditionalInfo(){
return $this->weight;
}
}
class ItemView extends ItemModel{
public function showItems(){
$this->setItems(new Bmw("test....", "BMW", 32, 1, 120));
$this->setItems(new Bmw("another....", "Z6", 16, 2, 10));
print_r($this->getItems()); //return BMW Object
// you can use somthing like this with BMW Object
print_r($this->getItems()[0]->getAdditionalInfo()."\n");
//or use my function
print_r($this->getItemsAsArray());
// or
foreach($this->getItemsAsArray() as $getItemsAsArray) {
foreach($getItemsAsArray as $key => $value) {
print_r($key."=".$value."\n");
}
}
}
}
$test = new ItemView();
$test->showItems();
?>

How do I pass objects into an array via getters/setters across another class in PHP OOP?

I don't understand how to pass the InvoiceItem objects instantiated in the ProcessInvoice class back to my array for output to the page.
See output at bottom of post. It should output all 3 items in the array and the grand invoice total.
Am I using the $this keyword wrong?? How to pass back the objects to the invoiceItems array in the Invoice class?
class InvoiceItem {
private $id;
private $itemQuanity;
private $itemPrice;
private $itemDescrip;
// Getters and Setter here for above 4 attributes
public function calculateItemTotal() {
$total = $this->itemPrice * $this->itemQuanity;
return $total;
}
public function display() {
echo "Item ID: $this->id // Item Quanity: $this->itemQuanity // Item Price: $this->itemPrice // Item Description: $this->itemDescrip // Total: $$this->total<br>";
}
}
class Invoice {
private $invoiceItems;
public function __construct() {
$item = new InvoiceItem();
$this->invoiceItems = array($item);
}
public function getInvoiceItems()
{
return $this->invoiceItems;
}
public function setInvoiceItems($invoiceItems)
{
$this->invoiceItems = $invoiceItems;
return $this;
}
public function calculateInvoice() {
foreach ($this->invoiceItems as $item_y) {
$invoiceTotal = $invoiceTotal += $item_y->calculateItemTotal();
}
echo "Invoice Total: $$invoiceTotal ";
}
public function displayInvoice() {
foreach ($this->invoiceItems as $item_x) {
$item_x->display();
}
return $this->calculateInvoice();
}
}
class ProcessInvoice {
private $invoice;
public function __construct() {
$this->invoice = new Invoice();
}
public function getInvoice()
{
return $this->invoice;
}
public function setInvoice($invoice)
{
$this->invoice = $invoice;
return $this;
}
function createInvoiceItems() {
$item1 = new InvoiceItem();
$item1->setId(1);
$item1->setItemPrice(1.66);
$item1->setItemQuanity(2);
$item1->setItemDescrip("item example");
$item2 = new InvoiceItem();
$item2->setId(2);
$item2->setItemPrice(34.99);
$item2->setItemQuanity(1);
$item2->setItemDescrip("bla bla");
$item3 = new InvoiceItem();
$item3->setId(3);
$item3->setItemPrice(2.24);
$item3->setItemQuanity(1);
$item3->setItemDescrip("Another item");
// SOMETHING WRONG HERE?!
$this->invoice->setInvoiceItems($item1, $item2, $item3);
}
function runProcess() {
$invoice_x = new Invoice();
$this->createInvoiceItems();
$invoice_x->displayInvoice();
}
}
Output: (from a "test drive" class not in this post - Simply calls the runProcess() method in the ProcessInvoice class)
Item ID: // Item Quanity: // Item Price: // Item Description: // Total: $
Invoice Total: $0
If Invoice::$invoiceItems is an array, you need to add invoices to it, you are just overwriting the property.
Create:
public function addInvoiceItem(InvoiceItem $invoiceItem)
{
$this->invoiceItems[] = $invoiceItem;
return $this;
}
And if you need to add several, you call the same method several times:
$this->invoice->addInvoiceItem($item1)
->addInvoiceItem($item2)
->addInvoiceItem($item3);
Additionally, your constructor doesn't appear to make a lot of sense. Why are you creating an array with an empty InvoiceItem?
Better just do this, and start with a properly empty array:
private $invoiceItems = [];

Managing collection of items through adding/removing

I want have an in-memory data structure to be able to add or remove an item (in this instance a student) into some sort of table (just like a shopping cart) from the collection class I have created. At the moment, it just displays students. For instance, if I click add student, it will pop up below, and I can delete this student from below also.
How I could implement this?
Here is my Member.php class
<?php
class Member {
private $name;
private $age;
private $gender;
private $course;
public function __construct($name,$age, $gender, $course){
$this->name = $name;
$this->age = $age;
$this->gender = $gender;
$this->course = $course;
}
public function setName($name) { //Sets the age value
$this->name = $name;
}
public function setAge($age) { //Sets the age value
$this->age = $age;
}
public function setGender($gender) { //Sets the gender value
$this->gender = $gender;
}
public function setCourse ($course) {
$this->course = $course;
}
public function getName() { //Gets the name value
return $this->name;
}
public function getAge() { //Gets the age value
return $this->age;
}
public function getGender() { //Gets the gender value
return $this->gender;
}
public function getCourse() {
return $this->course;
}
}
?>
Here is my ObjectCollection.php
<?php
class ObjectCollection
{
//This is an array to hold line items
private $items_array ;
private $itemCounter; //Count the number of items
public function __construct() {
//Create an array object to hold line items
$this->items_array = array();
$this->itemCounter=0;
}
public function getItemCount(){
return $this->itemCounter;
}
public function addItem($item) {
$this->itemCounter++;
$this->items_array[] = $item;
}
public function getItem($index) {
return $this->items_array[$index];
}
}
?>
And finally displaying this through testcollection.php
<?php
$ObjColl = new ObjectCollection();
$member1 = new Member("Jessica Davidson", 21, "Female", "Computing");
$ObjColl->addItem($member1);
$member2 = new Member("Lucy Barnes", 22, "Female", "History");
$ObjColl->addItem($member2);
$member3 = new Member("Mark Smith", 24, "Male", "Social Science");
$ObjColl->addItem($member3);
for($i = 0;$i < $ObjColl->getItemCount();$i++){
$item = $ObjColl->getItem($i);
if ($item instanceof Member) {
print "<br> University Member: ";
}
print "Name: " . $item->getName();
print ". Age: " . $item->getAge();
print ". Gender: " . $item->getGender();
print ". Enrolled on: " .$item->getCourse() . " course<br>";
}
?>
At first if your ObjectCollection must collect only objects of Member class, use parameter type declaration. It’s good practice in OOP.
public function addItem(Member $item)
At second if you want work with ObjectCollection like with array, implement ArrayAccess and Iterator interfaces.
Example
<?php
class Member{
private $__name;
public function __construct($name){
$this->__name = $name;
}
public function getName(){
return $this->__name;
}
}
class MemberCollection implements ArrayAccess, Iterator{
private $__Collection = [];
private $__position = 0;
public function __construct(){
}
public function offsetSet($offset, $value) {
if (is_null($offset)) {
$this->__Collection[] = $value;
} else {
$this->__Collection[$offset] = $value;
}
}
public function offsetExists($offset) {
return isset($this->__Collection[$offset]);
}
public function offsetUnset($offset) {
unset($this->__Collection[$offset]);
}
public function offsetGet($offset) {
return isset($this->__Collection[$offset]) ? $this->__Collection[$offset] : null;
}
function rewind() {
$this->__position = 0;
}
function current() {
return $this->__Collection[$this->__position];
}
function key() {
return $this->__position;
}
function next() {
++$this->__position;
}
function valid() {
return isset($this->__Collection[$this->__position]);
}
public function addItem(Member $Member){
$this->offsetSet(null, $Member);
}
}
$MC = new MemberCollection();
$Member1 = new Member('Name 1');
$Member2 = new Member('Name 2');
$MC->addItem($Member1);
$MC->addItem($Member2);
foreach ($MC as $Member){
echo '<br>' . $MC->key() . ':<br>';
var_dump($Member->getName());
}
unset($MC[0]); //Delete member from collection
?>

Get single value from an array

I have below array result
Array ( [0] => Item Object ( [name:protected] => My Super Cool Toy [price:protected] => 10.99 ) )
I need to get [name:protected] => My Super Cool Toy from this array.
Please tell me how to get it,
I will paste my classes below
class ShoppingCart
{
private $items = array();
private $n_items = 0;
function addItem( Item $item )
{
$this->items[] = $item;
$this->n_items = $this->n_items + 1;
print_r($this->items);
}
}
and
class Item {
protected $name;
protected $price;
public function __construct($name, $price) {
$this->name = $name;
$this->price = $price;
}
public function getName() {
echo "item is $this->name";
return $this->name;
}
public function getPrice() {
return $this->price;
}
}
and
require_once('AddingMachine.php');
require_once('item.php');
//$arrayofnumbers = array(100,200);
$objectname = new ShoppingCart();
$objectname->addItem(new Item('My Super Cool Toy', 10.99));
$obname = new Item($items,44);
$obname->getName();
Thanks
If I got it correctly, you got this array in ShoppingCart class, in method addItem, so to access it you just use corresponding getter method, e.g.:
$this->items[0]->getName();
You can try :
$objectname = new ShoppingCart();
$objectname->addItem(new Item('My Super Cool Toy', 10.99));
foreach ( $objectname->getItems() as $item ) {
echo $item->getName(), PHP_EOL;
}
Modified Class
class ShoppingCart {
private $items = array();
private $n_items = 0;
function addItem(Item $item) {
$this->items[] = $item;
$this->n_items = $this->n_items + 1;
}
function getItems($n = null) {
return $n === null ? $this->items : (isset($this->items[$n]) ? : $this->items[$n]);
}
}

Increase quantity when adding same Option

I have managed to implement OOP of Cart Basket
An Item contain 1 or more options.
If I add same OptionID again then the number of quantity should increase rather than creating another Option Object. How can that be done?
If I add same ItemID again, it should refuse to create another Item object.
Also is my OOP is good?
class Cart {
public $item = array();
public function addItem($id) {
$item = new Item();
$item->setItem($id);
$this->item[] = $item;
return $item;
}
}
class Item {
private $id = array();
private $option = array();
public function setItem($id) {
$this->id = $id;
return $this;
}
public function addOption($id) {
$option = new Option();
$option->setOption($id);
$this->option[] = $option;
}
}
class Option {
private $quantity;
private $id;
public function setOption($id) {
$this->quantity = 1;
$this->id = $id;
return $this;
}
}
$cart = new Cart();
//ItemID 10
$item = $cart->addItem(10);
//OptionID
$item->addOption(11);
$item->addOption(22);
$item->addOption(22); //should increase quantity
//It should not create another object because we already have Item Object of ItemID10
$item = $cart->addItem(10);
$Shop = $cart;
echo "<pre>";
print_r($Shop);
echo "</pre>";
If you can have only one item with the unique id in the cart - then rewrite the addItem() method like this:
public function addItem($id) {
$result = false;
if (empty($this->item[$id])) {
$item = new Item();
$item->setItem($id);
$this->item[$id] = $item;
$result = $item;
}
return $result;
}
The same is with addOption() method:
public function addOption($id) {
if (empty($this->option[$id])) {
$option = new Option();
$option->setOption($id);
$this->option[$id] = $option;
}
else {
$this->option[$id]->setQuantity($this->option[$id]->getQuantity() + 1);
}
}
And of course you should implement setQuantity() and getQuantity() methods in Option class.
Hope this helps.
Partialy rewrote the code and tested:
<?php
class Cart {
public $items = array();
public function addItem($id) {
if(array_key_exists($id, $this->items)){
$item = $this->items[$id];
}else{
$item = new Item($id);
$this->items[$id] = &$item;
}
return $item;
}
}
class Item {
private $id;
private $options = array();
public function __construct($id) {
$this->id = $id;
return $this;
}
public function addOption($id) {
if(array_key_exists($id, $this->options)){
$this->options[$id]->addQuantity();
}else{
$option = new Option($id);
$this->options[$id] = $option;
}
}
}
class Option {
private $quantity;
private $id;
public function __construct($id) {
$this->quantity = 1;
$this->id = $id;
return $this;
}
public function addQuantity()
{
$this->quantity++;
}
}
$cart = new Cart();
//ItemID 10
$item = $cart->addItem(10);
//OptionID
$item->addOption(11);
$item->addOption(22);
$item->addOption(22); //should increase quantity
//It should not create another object because we already have Item Object of ItemID10
$item = $cart->addItem(10);
$Shop = $cart;
echo "<pre>";
print_r($Shop);
echo "</pre>";
?>

Categories