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();
?>
Related
I am not sure why this isn't working, not sure if it's bad code or if I'm trying something wrong. Any input would be appreciated.
Here is the code.
Class CustomizerNick {
private $settingName;
private $settingRefresh;
private $title;
public $id;
public $label;
public $sectionChoose;
public $settingLink;
public $name;
private $priority;
public function setSettings($setName, $setR) {
$this->settingName = $setName;
$this->settingRefresh = $setR;
return $this;
}
public function setControl($id, $label, $choose, $link) {
$this->id = $id;
$this->label = $label;
$this->sectionChoose = $choose;
$this->settingLink = $link;
return $this;
}
public function setSection($name, $priority) {
$this->name = $name;
$this->priority = $priority;
return $this;
}
public function addSection($wp_customize) {
$wp_customize->add_section($this->name, array("title" =>"testing","priority" => $this->priority));
return $this;
}
private function addSetting($wp_customize) {
$wp_customize->add_setting($this->settingName, array("default" => "", "transport" => $this->settingRefresh));
}
public function addControl($wp_customize, $ob) {
$wp_customize->add_control($ob);
}
public function mainFunc($wp_customize, $ob){
$this->addSetting($wp_customize);
$this->addControl($wp_customize, $ob);
$this->addSection($wp_customize);
return $this;
}
};
function functionName($wp_customize) {
$img2 = new CustomizerNick;
$img2->setSettings("grid-pic-2", "refresh")->setControl("picture", "second-grid-item", "a named section", "grid-pic-2");
$img2->setSection("a named section", "5");
$ob = new WP_Customize_Image_Control($wp_customize, $img2->id, array( "label" => $img2->label, "section" => $img2->sectionChoose, "settings" => $img2->settingLink));
$img2->mainFunc($wp_customize, $ob);
}
It is not showing any errors, but it is not appearing in the customization tab, not sure if I called the built in wp object right. All the objects are there but doesn't seem to giving any output.
i would like to push some arrays into arrays and save it in a session.
And i tried to do this in a php class. I'm new to that so i made some mistakes and can't help me out.
my index.php:
<?php
session_start();
include("./cart.php");
//bezeichnung, preis, attribut
$myOrder = new Cart('17', 0.50, 'Book1');
$myOrder1 = new Cart('18', 1.50, 'Book2');
$_SESSION['products'] = array();
array_push($_SESSION['products'], $myOrder, $myOrder1);
echo '<pre>';
print_r($_SESSION['products']);
echo '</pre>';
my cart.php:
<?php
class Cart {
private $name;
private $price;
private $attr;
public function __construct($name, $price, $attr) {
$this->name = $name;
$this->price = $price;
$this->attr = $attr;
}
public function getName(){
return $this->name;
}
public function getPrice(){
return $this->price;
}
public function getAttr(){
return $this->attr;
}
}
i get something like this:
The part :Cart:private is really not good. This should be juest name,price and attr. I think i'm pushing the whole object into the array. How can i avoid this ?
Array
(
[0] => Cart Object
(
[name:Cart:private] => 17
[price:Cart:private] => 0.5
[attr:Cart:private] => Book1
)
[1] => Cart Object
(
[name:Cart:private] => 18
[price:Cart:private] => 1.5
[attr:Cart:private] => Book2
)
)
You can do a public method in your Cart class that will return all needed properties as an array.
class Cart {
private $name;
private $price;
private $attr;
public function __construct($name, $price, $attr) {
$this->name = $name;
$this->price = $price;
$this->attr = $attr;
}
public function getName(){
return $this->name;
}
public function getPrice(){
return $this->price;
}
public function getAttr(){
return $this->attr;
}
public function toArray(){
return array(
'name' => $this->getName(),
'price' => $this->getPrice(),
'attr' => $this->getAttr(),
);
}
}
Now in your index.php you can do:
array_push($_SESSION['products'], $myOrder->toArray(), $myOrder1->toArray());
I've been doing a project in PHP for the last few hours and I have encountered into a problem.
The problem is I don't know how to access private variables in a class and I can't find it online.
Example:
<?php
class Example{
private $age;
public function __construct() {
$age = 14;
$this->checkAge();
}
private function checkAge() {
if($this->$age > 12)
echo "welcome!";
}
}
$boy = new Example();
?>
As far as I know, I should be able to access the variable with $this->$age but it isn't working.
Thank you.
EDIT: Got it working with help of the awesome stackoverflooooooooow community, this is how a working one looks.
<?php
class Example{
private $age;
public function __construct() {
$this->age = 14;
$this->checkAge();
}
private function checkAge() {
if($this->age > 12)
echo "welcome!";
}
}
$boy = new Example();
?>
Look at this approach.
first: create Entity that stores and retrieves data inside of private $attributes array, and with magic __set(), __get() You can also do like: $object->variable = 123
second: extend Entity with Human class and add some function specific to child class (for example hasValidAge()):
<?php
class Entity {
private $attributes;
public function __construct($attributes = []) {
$this->setAttributes($attributes);
}
public function setAttribute($key, $value) {
$this->attributes[$key] = $value;
return $this;
}
public function setAttributes($attributes = []) {
foreach($attributes AS $key => $value) {
$this->setAttribute($key, $value);
}
}
public function getAttribute($key, $fallback = null) {
return (isset($this->attributes[$key]))?
$this->attributes[$key] : $fallback;
}
public function __get($key) {
return $this->getAttribute($key);
}
public function __set($key, $value) {
$this->setAttribute($key, $value);
}
}
class Human extends Entity {
public function __construct($attributes = []) {
$this->setAttributes($attributes);
$this->checkAge();
}
public function hasValidAge() {
return ($this->getAttribute('age') > 12)? true : false;
}
}
$boy = new Human(['name' => 'Mark', 'age' => 14]);
if($boy->hasValidAge()) {
echo "Welcome ".$boy->name."!";
}
?>
p.s. I've removed echo "Welcome!" part from constructor because it's not cool to do echo from model object, in our example Human is model of Entity.
I'm learning OOP, and got a little problem here with not understanding the code.
Here it is.
class ShopProduct {
private $title;
private $producerMainName;
private $producerFirstName;
protected $price;
private $discount = 0;
function __construct( $name, $firstName, $mainName, $price) {
$this->title = $name;
$this->producerFirstName = $firstName;
$this->producerMainName = $mainName;
$this->price = $price;
}
public function getProducer() {
return "{$this->producerMainName} "."{$this->producerFirstName} \n ";
}
public function setDiscount($num){
$this->discount = $num;
}
public function getDiscount() {
return $this->discount;
}
public function getTitle() {
return $this->title;
}
public function getPrice() {
return ($this->price - $this->discount);
}
public function getSummaryLine() {
$base = "{$this->title} ( {$this->producerMainName}, ";
$base .= "{$this->producerFirstName} )";
return $base;
}
}
class CDProduct extends ShopProduct {
private $playLength = 0;
public function __construct($title, $firstName, $mainName, $price, $playLength) {
parent::__construct($title, $firstName, $mainName, $price);
$this->playLength = $playLength;
}
public function getPlayLength() {
return $this->playLength;
}
public function getSummaryLine() {
$base = parent::getSummaryLine();
$base .= ": {$this->playLength()} minutes";
return $base;
}
}
class BookProduct extends ShopProduct {
private $numPages = 0;
public function __construct($title, $firstName, $mainName, $price, $numPages) {
parent::__construct($title, $firstName, $mainName, $price);
$this->numPages = $numPages;
}
public function getNumberOfPages() {
return $this->numPages;
}
public function getSummaryLine() {
$base = parent::getSummaryLine();
$base .= ": {$this->numPages()} pages";
return $base;
}
}
class ShopProductWriter {
private $products = array();
public function addProduct($shopProduct){
if(! ($shopProduct instanceof ShopProduct) ){
die('object error');
}
$this->products[] = $shopProduct;
}
public function write($shopProduct) {
foreach($this->products as $shopProducts){
$str = "{$shopProduct->getTitle()}: "."{$shopProduct->getProducer()}"." {$shopProduct->getPrice()}$ \n";
}
print $str;
}
}
$product = new CDProduct('Song is the rythm','Zyxel','Beatz',50, 60.33);
$write = new ShopProductWriter();
$write->addProduct($product);
$write->write($product);
The problem is here
class ShopProductWriter {
private $products = array();
public function addProduct($shopProduct){
if(! ($shopProduct instanceof ShopProduct) ){
die('object error');
}
$this->products[] = $shopProduct;
}
public function write($shopProduct) {
foreach($this->products as $shopProducts){
$str = "{$shopProduct->getTitle()}: "."{$shopProduct->getProducer()}"." {$shopProduct->getPrice()}$ \n";
}
print $str;
}
}
As you see there is condition - if the object is not ShopProduct type - goes error.
But as you see i'm creating CDProduct object.
$product = new CDProduct('Song is the rythm','Zyxel','Beatz',50, 60.33);
$write = new ShopProductWriter();
$write->addProduct($product);
$write->write($product);
It should show error. Anybody can say me what i'm doing wrong?
Objects of CDProduct are also of type ShopProduct. In the class definition:
class CDProduct extends ShopProduct {
So it is an object of both types.
http://php.net/manual/en/language.oop5.inheritance.php
If an object extends a parent or implements an interface, it can be considered of that type also.
http://php.net/manual/en/language.operators.type.php
You got already feedback about why a CDProduct is a ShopProduct, so I just add another hint on some code you've written where PHP has already support for:
public function addProduct($shopProduct){
if(! ($shopProduct instanceof ShopProduct) ){
die('object error');
}
$this->products[] = $shopProduct;
}
Instead of doing the check on your own, you can just make use of Type Hinting to reduce your code and make it more expressive:
public function addProduct(ShopProduct $shopProduct) {
$this->products[] = $shopProduct;
}
I hope this helps as you wrote you're currently learning about OOP.
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);